C - 瑞洛克投掷"Access violation reading location"



我正在使用Visual Studio 16.6.0。 在我的 C 程序的某些部分中,我有一个动态数组 (myvector(,我正在尝试调整它的大小以包含一定数量的元素(可变数量的记录(。使用完全相同的输入数据,有时此代码有效,或者在realloc执行中随机抛出">访问冲突读取位置"。 我的两个问题:

  1. 如果realloc有问题,错误控件不应该将其检测为返回的 NULL 吗?

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

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 reallocn");
free(myvector);
exit(EXIT_FAILURE);
}
else {
myvector = temp;
}          
}
}//while end

谢谢

正如上面的评论者所说,这是由于未由"\0"完成的字符串的realloc将一些垃圾字符附加到原始字符串中,并且它使附加到它的字符串大小的出站。

非常感谢您的帮助

相关内容

最新更新