为何使用calloc()分配5个int空间却可写入并读取6个元素?
为什么calloc分配5个int的内存却能读写6个元素?
我的代码
#include <stdio.h> #include <stdlib.h> int main(){ int *ptr; ptr=(int*)calloc(5,sizeof(int)); for(int i=0;i<6;i++){ printf("Enter the %d value:",i+1); scanf("%d",&ptr[i]); } printf("\n Elements in allocated memory\n\n"); for(int i=0;i<6;i++){ printf("The %d element is: %d\n",i+1,ptr[i]); } return 0; }
运行输出
Enter the 1 value:1 Enter the 2 value:2 Enter the 3 value:3 Enter the 4 value:4 Enter the 5 value:5 Enter the 6 value:6 Elements in allocated memory The 1 element is: 1 The 2 element is: 2 The 3 element is: 3 The 4 element is: 4 The 5 element is: 5 The 6 element is: 6
我用calloc分配了仅能容纳5个int类型元素的内存空间,但实际运行时却能成功写入并读取6个元素,这是为什么?
解答
这是典型的未定义行为,具体原因和风险如下:
- 你调用
calloc(5, sizeof(int))只申请了对应5个int的内存,ptr[5]已经超出了这块内存的合法访问范围,属于内存越界访问。 - 程序没立刻崩溃只是巧合:操作系统的内存保护机制不会逐字节检查每一次内存访问,这块越界的地址刚好属于当前进程的地址空间,且暂时没有被其他数据占用,所以读写操作没触发错误,但这种情况完全不可靠。
- 这种行为极度危险:后续如果有其他内存分配操作(比如malloc、realloc),很可能会覆盖你越界写入的数据,导致程序崩溃、数据错乱,甚至引发安全漏洞。
- 修复方法:要么把循环的终止条件改成
i<5,要么用realloc把内存扩容到能容纳6个int的大小:
// 扩容示例 ptr = realloc(ptr, 6 * sizeof(int)); if (ptr == NULL) { // 处理内存分配失败的情况 perror("realloc failed"); exit(EXIT_FAILURE); }
内容的提问来源于stack exchange,提问作者user20470572
相关产品推荐
相关产品推荐

