繁体   English   中英

使用realloc时发生运行时错误:“ _CrtIsValidHeapPointer(pUserData),dbgheap.c”

[英]Run time error while using realloc: “ _CrtIsValidHeapPointer(pUserData), dbgheap.c”

以下代码是用C ++编写的,但使用来自stdlib.h的realloc,因为我对std :: vector不太了解。

无论如何,我得到了这个奇怪的运行时错误“ _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)));

_grade和_students都是用new创建的,完全没有问题。 问题仅在于尝试重新分配_students时。

任何输入将受到欢迎。

您不能混合使用分配器-如果使用operator new[]分配内存,则必须使用operator delete[]取消分配内存。 您不能使用free()realloc()或任何其他内存分配器(例如Windows的GlobalFree() / LocalFree() / HeapFree()函数)。

realloc()只能重新分配使用malloc()系列函数( malloc()calloc()realloc() )分配的内存区域。 试图realloc任何其它存储块是不确定的行为,在这种情况下,你很幸运,C运行时能够抓住你的错误,但如果你运气不好的话,你可能在一些随机点默默地破坏内存,再到后来坠毁“不可能”状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM