为什么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) {
        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。 >