Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My main.c contents :

int main(int argc, char **argv)  
{  
    void * tmp = malloc(8);  
    ((double *)tmp)[0] = 100;  
    ((double *)tmp)[1] = 102;  
    printf("tmp %p
", tmp);  
    printf("tmp[0] %d %f %p
", sizeof(((double *)tmp)[0]), ((double *)tmp)[0], &((double *)tmp)[0]);  
    printf("tmp[1] %d %f %p
", sizeof(((double *)tmp)[1]), ((double *)tmp)[1], &((double *)tmp)[1]);  
    return EXIT_SUCCESS;  
}  

=========================OUTPUT=========================  
tmp 0xee8010  
tmp[0] 8 100.000000 0xee8010  
tmp[1] 8 102.000000 0xee8018  
========================================================

First, I did allocate 8 bytes of memory in variable tmp and I assigned number 100 to address 0xee8010.

((double *)tmp)[0] = 100;  

I also assign number 102 to unallocated memory 0xee8018.

((double *)tmp)[1] = 102;  

But I didn't see any error message at build-time nor at runtime. Why not?

Please help me understand this. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
787 views
Welcome To Ask or Share your Answers For Others

1 Answer

Writing to unallocated or writing beyond bounds of allocated memory results in Undefined Behavior(UB) which does not necessarily warrant a crash.
An Undefined behavior means that any behavior can be observed the compiler implementation does not need to do anything specific(like a segmentation fault as you expect) when an UB occurs.

But I didn't see any error message at the build time and runtime.

You get compile time errors for code which do not abide to the language standard. In this case the code abides to the language standard but does something who's outcome is not defined by the language standard.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...