Feb 12, 2009

memory address queation

#include
main()
{
char a[]="Hello";
char b[]="Hello";

char *p="hi";
char *q="hi";

if(a==b)
printf("Both are equal\n");
else
printf("Not equal\n");

if(p==q)
printf("Both are equal %c",*p);
else
printf("Not equal\n");
}
Not equal for the first. The two arrays are allocated separately, and the equality operator tests for whether the pointer points to the same address in memory. Two arrays in different places means that is a no.
The second, however, does produce equal pointers on my default version of gcc (I suspect there are some compilers and/or optimization settings for which this would NOT be true). The reason is because the compiler has optimized the common string literal in both places by storing it at one place in memory. That place is incidentally within the program's code segment, which means if you try touching it BAM segfault for you.

No comments:

Post a Comment