为什么realloc不调整数组的内存大小?
我在学习C,我看到了一些我不清楚的东西 代码如下:为什么realloc不调整数组的内存大小?,c,memory-management,realloc,C,Memory Management,Realloc,我在学习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) { pri
#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);
}
你能给我解释一下这是如何工作的吗?重新分配后,你忘了用
newArr
分配arr
,然后打印无效arr
的值。(UB第1号)
其次,即使您在
printf
中分配它(或仅将arr
更改为newArr
),您也将访问数组边界之外的元素-即UB no 2内存尚未回收/重用。谢谢,我以为是这样,但我想确定一下,因为我在进程监视器上看到它被释放
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