[cfe-dev] [Clang] memory allocation

Mohammad Norouzi via cfe-dev cfe-dev at lists.llvm.org
Tue Nov 26 03:59:51 PST 2019


Hi,

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

I am using a sample program (below) to show the problem.

When I compile the program with clang -O0, variable j in function ok has
the same memory address as variable solutions in function nqueens. Function
ok is called inside function nqueens, which means that the life time of the
variables intersect.

Compiling the program with gcc or clang -O1, however, they are assigned
different memory addresses.

Any help is appreciated!

==================SAMPLE PROGRAM====================

#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);
}

==================END SAMPLE PROGRAM====================

Best Regards,
Mohammad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20191126/8d3cccc8/attachment.html>


More information about the cfe-dev mailing list