【问题标题】:Why is realloc not resizing the memory of my array? [duplicate]为什么 realloc 不调整我的数组的内存大小? [复制]
【发布时间】: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


【解决方案1】:

重新分配后,您忘记将arr 分配给newArr,然后从无效的arr 中打印值。 (UB 1 号)

其次,即使您在 printf 中分配它(或仅将 arr 更改为 newArr),您也将访问数组边界之外的元素 - 这是 UB no 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 2012-03-17
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    相关资源
    最近更新 更多