Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么realloc不调整数组的内存大小?_C_Memory Management_Realloc - Fatal编程技术网

为什么realloc不调整数组的内存大小?

为什么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

我在学习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);
}

你能给我解释一下这是如何工作的吗?

重新分配后,你忘了用
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