首页 > 解决方案 > 为什么 realloc 会破坏价值?

问题描述

#include<stdio.h>
#include<stdlib.h>
void main()
{
    int* list_of_numbers;
    list_of_numbers = (int*)malloc(1);
    list_of_numbers[0] = 10;
    printf("Value at 0 before realloc: %d", list_of_numbers[0]);
    list_of_numbers = (int*)realloc(list_of_numbers, 2 * sizeof(int));
    printf("Value at 0 after realloc: %d", list_of_numbers[0]);//this one prints -83920310 instead of 10

    system("pause");
}

我的任务是要求我为一个数字分配内存并且效果很好然后我需要重新分配它以适应 2 个数字,一旦我这样做,我的第一个值就会被随机值替换。为什么?以及如何修复:D

标签: cmemoryallocation

解决方案


malloc(1)太小而无法容纳int,因此在此处写入未定义行为。只是巧合,它一开始似乎有效。做malloc(sizeof(int))malloc(sizeof(*list_of_numbers))代替。


推荐阅读