简体   繁体   中英

What if the counter exceeds the memory allocated by malloc or calloc

I use following command in C to allocates 80 bytes (in a 64bit system) to d.

double *d = calloc(10, sizeof(double));

And using following loop to initialize d

for (k=0;k<11;k++){
d[k] = k;
}

When I run the program, there is no error. but I feel since the upper limit on k is 11 , there should be something wrong as d is array of length 10. Please let me know why the program is executed with no error. Thanks in advance.

This is undefined behavior . There might be an error, and it might be silently ignored by the OS, when you break the rules - all bets are off.

What actually happens in the code depends on the OS, the compiler and the architecture you run it on, which might be tolerant to this violation, crash or do something else, the point is - the resulting behavior is undefined.

I believe that C and C++ doesn't do boundary checks with array and pointers as long as it is in the program stack. I believe it throws segmentation fault when access is outside the program stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM