c - Does this program only crash on x32 because of alignment differences? -


the following code taken here:

#include<stdio.h>  int main() {     char = 30;     char j = 123;     char* p = &i;     printf("pointer points to: %p\n", p);     void* q = p;     int * pp = q;   /* unsafe, legal c, not c++ */      printf("%d %d\n",i,j);     *pp = -1;   /* overwrite memory starting @ &i */     printf("%d %d\n",i,j);     printf("pointer points to: %p\n", p);     printf("%d\n", *p); } 

on x32 linux machine crashes in last line. on x64 linux not crash. because pointers 4 bytes on x32 , 8 bytes on x64 , due alignment requirements there max 6 bytes hole between char j , char *p on x64 machine overwritten *pp = -1 , therefore nothing happens *p on x32 machine hole maximum 2 bytes *pp = -1 overwrites fist 2 bytes of char *p resulting in segmentation fault when dereferencing? reasoning correct or idiotic?

the reasoning not idiotic, not guaranteed correct.

the layout of function stack not fixed might think. while stack pointer register allowed have address mod 4 or mod 8, depending on alignment, compiler not required follow specific alignment. there not guarantee data somewhere on stack. might reside in registers!

the stack alignment have in mind part of procedure call standard, says how stack has before 1 function calls function , wants transfer data via stack. in case compiler required align , pad data , make sure address of pointer passed parameter resides on 4/8 byte boundary.

in example: x64 executable might run, because compiler keeps p in register , not on stack, overwriting stack not affect p, if memset whole stack zero. p valid address can dereferenced.

so, code run fine on 32 bit machine, or crash on 64 bit machine. compiler , optimization settings determine result more architecture.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -