Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,因此它是on-topic,用于堆栈溢出。
                        
                        3个月前关闭。
                                                                                            
                
        
#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

最佳答案

malloc(1)太小而无法容纳int,因此在其中写一个时存在未定义行为。刚开始它似乎只是出于巧合。改为使用malloc(sizeof(int))malloc(sizeof(*list_of_numbers))

关于c - 为什么重新分配会弄乱值? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59058030/

10-11 22:10
查看更多