[llvm-dev] [Clang] memory allocation

Mohammad Norouzi via llvm-dev llvm-dev at lists.llvm.org
Wed Nov 20 05:44:20 PST 2019


Hi,

Could anyone please help me understand why Clang reallocates the same
memory address for different variables while their lifetime intersect?

Here is an example code:


#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <alloca.h>


/* Checking information */

static int solutions[] = {
        1,
        0,
        0,
        2,
        10, /* 5 */
        4,
        40,
        92,
        352,
        724, /* 10 */
        2680,
        14200,
        73712,
        365596,
};
#define MAX_SOLUTIONS sizeof(solutions)/sizeof(int)

int total_count;
int sharedVar = 0;

int ok(int n, char *a)
{
     int i, j;
     char p, q;
     printf("jjjjjjjjj: %d, %p\n", n,&j);
     for (i = 0; i < n; i++) {
           p = a[i];


 for (j = i + 1; j < n; j++) {
      q = a[j];
      if (q == p || q == p - (j - i) || q == p + (j - i))
         return 0;
 }
     }
     return 1;
}

void nqueens (int n, int j, char *a, int *solutions)
{
int i,res;
  sharedVar = sharedVar * j - n;
if (n == j) {
/* good solution, count it */
     *solutions = 1;
      return;
}
printf("solutions: %d, %p\n", j, &solutions);
*solutions = 0;

      /* try each possible position for queen <j> */
for (i = 0; i < n; i++) {
     a[j] = (char) i;
     if (ok(j + 1, a)) {
         nqueens(n, j + 1, a,&res);
         *solutions += res;
     }
  }
}

int main()
{
  int size = 3;
char *a;
// printf("total_count: %p\n", &total_count);
total_count=0;
a = (char *)alloca(size * sizeof(char));
printf("Computing N-Queens algorithm (n=%d) ", size);
  sharedVar = -5;
   nqueens(size, 0, a, &total_count);
        printf("completed!\n");
  printf("sharedVar: %d\n", sharedVar);
}



When I compile the program with clang -O0 variable j in function ok has the
same memory address as th variable solutions in function nqueens.

However, compiling it with gcc, they have different memory addresses.

Any help is appreciated!

Best Regards,
Mohammad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20191120/21c6b115/attachment.html>


More information about the llvm-dev mailing list