问题描述
我正在学习C,但我发现有些不清楚的东西。
这是代码:
#include <stdlib.h>
#include <stdio.h>
int main(void) {
printf("I'm using malloc\n");
int size = 10000000;
int *arr = (int *)malloc(size * sizeof(int));
if (arr == NULL) {
printf("memory Could not be allocated\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < size; i++) {
arr[i] = i;
}
printf("Check the memory of the process\n");
int c;
scanf("%d",&c);
printf("I'm using realloc\n");
int *newArr = realloc(arr,5 * sizeof(int));
if (newArr == NULL) {
printf("memory Could not be allocated\n");
exit(EXIT_FAILURE);
}
int d;
printf("Check the memory of the process\n");
scanf("%d",&d);
for (int i = 0; i < 15; i++) {
printf("%d\n",arr[i]);
}
free(newArr);
}
如果我检查运行在顶部的进程,则可以发现进程的内存由于realloc
操作而缩小,我没想到的是最后一个for
循环实际上是打印arr
中的前15个数字。由于缺少5到15个元素,我期望出现错误。
I'm using malloc
Check the memory of the process
45
I'm using realloc
Check the memory of the process
45
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
您能告诉我这是怎么回事吗?
解决方法
重新分配后,您忘记为arr
分配newArr
,然后从无效的arr
打印值。 (UB号1)
第二,即使您在arr
中将其分配(或仅将newArr
更改为printf
),您也将访问数组边界之外的元素-UB 2。 >