[Clang] memory allocation

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

[Clang] memory allocation

Tom Stellard via cfe-dev
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

_______________________________________________
cfe-dev mailing list
[hidden email]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev