重新分配抛出 "Access violation reading location"
realloc throws "Access violation reading location"
我正在使用 Visual Studio 16.6.0。
在我的 C 程序的某些部分,我有一个动态数组 (myvector),我试图调整它的大小以包含一定数量的元素(可变记录数)。使用完全相同的输入数据,有时这段代码可以工作,或者在 realloc
执行中随机抛出“访问违规读取位置” .
我的两个问题:
如果 realloc
有问题,错误控制不应该将其检测为返回的 NULL 吗?
最重要的是:我做错了什么?如果这是一个愚蠢的问题,我很抱歉,但我无法找出为什么这个 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 realloc\n");
free(myvector);
exit(EXIT_FAILURE);
}
else {
myvector = temp;
}
}
}//while end
谢谢
正如上面的评论者所说,这是由于 '\0' 未完成的字符串的重新分配将一些垃圾字符附加到原始字符串,这使得附加到它的字符串大小超出范围。
非常感谢您的帮助
我正在使用 Visual Studio 16.6.0。
在我的 C 程序的某些部分,我有一个动态数组 (myvector),我试图调整它的大小以包含一定数量的元素(可变记录数)。使用完全相同的输入数据,有时这段代码可以工作,或者在 realloc
执行中随机抛出“访问违规读取位置” .
我的两个问题:
如果
realloc
有问题,错误控制不应该将其检测为返回的 NULL 吗?最重要的是:我做错了什么?如果这是一个愚蠢的问题,我很抱歉,但我无法找出为什么这个 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 realloc\n");
free(myvector);
exit(EXIT_FAILURE);
}
else {
myvector = temp;
}
}
}//while end
谢谢
正如上面的评论者所说,这是由于 '\0' 未完成的字符串的重新分配将一些垃圾字符附加到原始字符串,这使得附加到它的字符串大小超出范围。
非常感谢您的帮助