【发布时间】:2020-10-23 14:25:34
【问题描述】:
我正在学习 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);
}
如果我检查使用 top 运行的进程,我可以看到进程的内存由于 realloc 操作而缩小,我没想到的是最后一个 for 循环实际上正在打印前 15来自arr 的号码。由于缺少 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
你能解释一下这是如何工作的吗?
【问题讨论】:
-
内存还没有被回收/重用。
-
谢谢,我以为是这样,但我想确定一下,因为我看到它在进程监视器上被释放了
标签: c memory-management realloc