微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么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。 >

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。