A block of code that is suppose to cause a bus error executes fine

  • A+
Category:Languages

I am currently reading Expert C Programmign - Deep C Secrets. On page 164 where the author was explaining Bus Error and Segmentation fault , he showed this line of code

union {    char a[10];   int i; } u ;  int * p = ( int * ) &(u.a[1]); *p = 17; /* the misaligned addr in p causes a bus error */ 

The above code is suppose to trigger a bus error, but when i ran it, it ran fine without any error. The author gave the below explanation

This causes a bus error because the array/int union ensures that character array "a" is also at a reasonably aligned address for an integer, so "a+1" is definitely not. We then try to store 4 bytes into an address that is aligned only for single-byte access. A good compiler will warn about misalignment, but it cannot spot all occurrences.

My understanding of the above statement is that , char is 1 byte and we are trying to place an int which is 4 byte on an index of char a[10] hence a bus error will occur ( am not sure if my understanding is right or wrong )

My question is why is the above code not causing a bus error.

Note: Am not a CS student,simple explanations will help.

Note: A question that looks smiliar to this question have already been asked, but am only specific to the above block of code.

 


I believe that the book is mistaken. The code causes undefined behaviour. Expecting any certain behaviour from it is therefore flawed. Also note that not all architectures can cause bus errors. If the book doesn't explain this fact, that doesn't speak for it either.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: