C compiler relocates pointer that overlaps another variable -


i doing experiments see how c allocates variables on stack. getting odd behavior following code. c appears growing stack downward, in following example, char c allocated in byte before short s. create int pointer bigrandp , point @ same location occupied c, "int" sees overlaps space on stack occupied s. try assign location referenced int pointer.

unsigned short namesum = 0; unsigned char smallrand = 0; unsigned int* bigrandp;  //the "int" pointed ip should overlap s bigrandp = (unsigned int*)(&smallrand); printf("%p %p %p\n", &namesum, &smallrand, bigrandp); printf("%u %u %u\n", smallrand, namesum, *bigrandp); *bigrandp = 0; printf("%p %p %p\n", &namesum, &smallrand, bigrandp); printf("%u %u %u\n", smallrand, namesum, *bigrandp);  0028ff1a 0028ff19 0028ff19 0 0 419430400 0028ff1a 0028ff19 0028ff00 0 0 4210788 

the printed results interesting. not assignment fail (the int pointed bigrandp not set 0), int pointer silently relocated point somewhere else further down stack. going on? c compiler's way of keeping me overwriting other variables overlapping pointers?

bigrandp pointer unsigned int.

you pointed unsigned char object, modified unsigned int object bigrandp points to.

apparently smallrand , bigrandp stored close each other in memory. trying modify sizeof (unsigned int) bytes of 1-byte object, clobbered part of pointer object itself.

bottom line: program's behavior undefined.

also, though isn't related behavior you're seeing, %p format requires void* argument. if want print other type of pointer, should convert void*:

printf("%p %p %p\n", (void*)&namesum, (void*)&smallrand, (void*)bigrandp); 

it's "work" or without casts on systems pointers have same representation, version casts more correct on systems.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -