<div dir="ltr"><div>Hi,</div><div><br></div><div>Could anyone please help me understand
why Clang reallocates the same memory address for different variables
while their lifetime intersect?</div><div><br></div><div>I am using a sample program (below) to show the problem. <br></div><div><br></div><div>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. <br></div><div><div><br></div><div>Compiling the program with gcc or clang -O1, however, they are assigned different memory addresses.</div><div><br></div><div>Any help is appreciated!</div></div><div><br></div><div>==================SAMPLE PROGRAM====================<br></div><div></div><div></div><div><br>#include <stdlib.h><br>#include <stdio.h><br>#include <memory.h><br>#include <alloca.h><br><br><br>/* Checking information */<br><br>static int solutions[] = {<br> 1,<br> 0,<br> 0,<br> 2,<br> 10, /* 5 */<br> 4,<br> 40,<br> 92,<br> 352,<br> 724, /* 10 */<br> 2680,<br> 14200,<br> 73712,<br> 365596,<br>};<br>#define MAX_SOLUTIONS sizeof(solutions)/sizeof(int)<br><br>int total_count;<br>int sharedVar = 0;<br><br>int ok(int n, char *a)<br>{<br> int i, j;<br> char p, q;<br> printf("jjjjjjjjj: %d, %p\n", n,&j);<br> for (i = 0; i < n; i++) {<br> p = a[i];<br> <br><br> for (j = i + 1; j < n; j++) {<br> q = a[j];<br> if (q == p || q == p - (j - i) || q == p + (j - i))<br> return 0;<br> }<br> }<br> return 1;<br>}<br><br>void nqueens (int n, int j, char *a, int *solutions)<br>{<br> int i,res;<br> sharedVar = sharedVar * j - n;<br> if (n == j) {<br> /* good solution, count it */<br> *solutions = 1;<br> return;<br> }<br>printf("solutions: %d, %p\n", j, &solutions);<br> *solutions = 0;<br><br> /* try each possible position for queen <j> */<br> for (i = 0; i < n; i++) {<br> a[j] = (char) i;<br> if (ok(j + 1, a)) {<br> nqueens(n, j + 1, a,&res);<br> *solutions += res;<br> }<br> }<br>}<br><br>int main()<br>{<br> int size = 3;<br> char *a;<br>// printf("total_count: %p\n", &total_count);<br> total_count=0;<br> a = (char *)alloca(size * sizeof(char));<br> printf("Computing N-Queens algorithm (n=%d) ", size);<br> sharedVar = -5;<br> nqueens(size, 0, a, &total_count);<br> printf("completed!\n");<br> printf("sharedVar: %d\n", sharedVar);<br>}<br></div><div><br></div><div>==================END SAMPLE PROGRAM====================</div><div><br></div><div>Best Regards,</div><div>Mohammad</div></div>