为什么重新分配会弄乱值?

问题描述 投票:0回答:1
#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

c memory allocation
1个回答
0
投票

malloc(1)太小,无法容纳int,因此写一个存在未定义的行为。碰巧它似乎一开始就起作用。改为执行malloc(sizeof(int))malloc(sizeof(*list_of_numbers))

© www.soinside.com 2019 - 2024. All rights reserved.