realloc抛出 "访问违规读取位置"

问题描述 投票:0回答:1

我使用的是Visual Studio 16.6.0。在我的C程序的某些部分,我有一个动态数组(myvector),我试图调整其大小以包含一定数量的元素(变量numberofrecords)。使用完全相同的输入数据,有时这段代码可以工作,或者随机抛出"进出违规读取位置"中 realloc 执行.我的两个问题。

  1. 如果有一个问题 realloc,错误控制不是应该检测到它是一个返回的NULL吗?

  2. 最重要的是:我做错了什么?如果这是一个愚蠢的问题,我很抱歉,但我找不到为什么这个重新分配会抛出随机异常,即使一次又一次地使用完全相同的输入。

    void* temp; //temporal pointer for realloc
    int* myvector = malloc(sizeof(int));

    int numberofrecords = 0;


    while(numberofrecords<100){  

       if (some_condition){
          numberofrecords++;
          temp = realloc(myvector, numberofrecords * sizeof(int));
          if (temp == NULL) { 
              printf("ERROR in realloc\n");
              free(myvector);
              exit(EXIT_FAILURE);
          }
          else {
              myvector = temp;
          }          
       }
    }//while end

谢谢您

c visual-studio memory realloc
1个回答
0
投票

正如上面的评论者所说,这是由于字符串的重新分配没有完成'\0'附加一些垃圾字符到原来的字符串,它使得附加到它得到的字符串大小的边界。

非常感谢您的帮助

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