简体   繁体   English

如果计数器超出了malloc或calloc分配的内存,该怎么办

[英]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. 我在C中使用以下命令为D分配80个字节(在64位系统中)。

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

And using following loop to initialize d 并使用以下循环初始化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. 但是我感觉由于k的上限是11 ,所以应该有问题,因为d是长度为10的数组。请让我知道为什么程序执行时没有错误。 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. 我相信C和C ++不会对数组和指针进行边界检查,只要它在程序堆栈中即可。 I believe it throws segmentation fault when access is outside the program stack. 我相信当访问不在程序堆栈之外时,它将引发分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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