Reputation: 81654
The following code is written in C++ but using realloc from stdlib.h because I don't know much about std::vector.
Anyway, I get this weird run time error " " _CrtIsValidHeapPointer(pUserData), dbgheap.c".
If you would like to see the whole method or code please let me know.
I have 2 classes, Student and Grades. Student contains
char _name[21];
char _id[6];
int _numOfGrades;
int* _grades;
float _avg;
and Grade simply contains
Student* _students;
int _numOfStudents;
while the following works
_grades = (int *)realloc(_grades,(sizeof(int)*(_numOfGrades+1)));
this will create that weird run time error:
_students = (Student *)realloc(_students,(sizeof(Student)*(_numOfStudents+1)));
Both _grades and _students are created with new with no problem at all. The problem is only while trying to realloc _students.
Any input will be welcome.
Upvotes: 2
Views: 2080
Reputation: 400454
You cannot mix allocators—if you allocate memory with operator new[]
, you must deallocate it with operator delete[]
. You cannot use free()
, realloc()
, or any other memory allocator (e.g. Windows' GlobalFree()
/LocalFree()
/HeapFree()
functions).
realloc()
can only reallocate memory regions which were allocated with the malloc()
family of functions (malloc()
, calloc()
, and realloc()
). Attempting to realloc
any other memory block is undefined behavior—in this case, you got lucky and the C runtime was able to catch your error, but if you were unlucky, you might silently corrupt memory and then later crash at some random point in an "impossible" state.
Upvotes: 1