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

Categories

0 votes
782 views
in Technique[技术] by (71.8m points)

c - No errors when writing outside allocated memory range

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...