运行时错误而使用的realloc:“_CrtIsValidHeapPointer(pUserData),dbgheap.c”
问题描述:
下面的代码是用C++编写,但使用stdlib.h中realloc的,因为我不知道很多有关的std ::向量。运行时错误而使用的realloc:“_CrtIsValidHeapPointer(pUserData),dbgheap.c”
无论如何,我得到这个奇怪的运行时错误“” _CrtIsValidHeapPointer(pUserData),dbgheap.c”。
如果你想看到整个方法或代码,请让我知道。
我有2个班,学生和成绩。学生包含
char _name[21];
char _id[6];
int _numOfGrades;
int* _grades;
float _avg;
和等级只包含
Student* _students;
int _numOfStudents;
而下面的工作
_grades = (int *)realloc(_grades,(sizeof(int)*(_numOfGrades+1)));
这将创建一个奇怪的运行时错误:
_students = (Student *)realloc(_students,(sizeof(Student)*(_numOfStudents+1)));
两个_grades和_students与新创建了一点问题都没有。问题只是在试图重新分配_students时。
任何输入将受到欢迎。
答
不能混合分配器,如果你有operator new[]
分配内存,你必须与operator delete[]
释放它。不能使用free()
,realloc()
,或任何其他内存分配器(例如Windows的GlobalFree()
/LocalFree()
/HeapFree()
功能)。
realloc()
仅可以重新分配,其被分配与malloc()
系列函数(malloc()
,calloc()
,和realloc()
)的存储器区域。试图realloc
任何其他内存块是未定义的行为 - 在这种情况下,你很幸运,并且C运行时能够捕获你的错误,但如果你不幸,你可能会默默地损坏内存,然后在某个随机点崩溃“不可能”状态。
是否有可能你有内存泄漏的地方,也许在代码是不相关的?看起来像损坏的内存堆。例如,如果您在分配的空间之外写入以前分配的分数,则可能发生这种情况。 – akonsu 2013-04-10 00:52:38
你说一个年级有2个成员,但是当你分配内存时,你只给一个(int)成员分配空间。 – 2013-04-10 01:02:29