[英]Dynamic memory allocation error
I have a char pointer as a private member of a class. 我有一个char指针作为类的私有成员。 I need to read record from a file and insert it into class array.
我需要从文件中读取记录并将其插入到类数组中。 First, I need to get number of record first then create a myStudent array during runtime.
首先,我需要先获取记录数,然后在运行时创建myStudent数组。 Then insert all the record in. But when I tried to initialize the name field using set method, it gave me Practise1(3278,0x7fff7287e300) malloc:error for object 0x100105578: incorrect checksum for freed object - object was probably modified after being freed.
然后插入所有记录。但是当我尝试使用set方法初始化name字段时,它给了我Practise1(3278,0x7fff7287e300)malloc:对象0x100105578的错误:已释放对象的校验和不正确-对象可能在释放后被修改。 set a breakpoint in malloc_error_break to debug error
在malloc_error_break中设置断点以调试错误
if i use debugger to run the program step-by-step, it works perfectly fine with no error, however if i run it normally, it gave me the above error. 如果我使用调试器逐步运行程序,则可以正常运行且没有错误,但是,如果我正常运行,则会出现上述错误。 (Sometimes it works, sometime it doesn't)
(有时有效,有时无效)
Here is a small portion of my code: 这是我的代码的一小部分:
myClass.h: myClass.h:
class myClass{
private:
char *name;
public:
myClass();
void setName(string);
}
myClass.cpp myClass.cpp
myClass:: myClass(){}
void myClass::setName(string x){
name = new char[x.length()+1]; //my xcode give me signal SIGBART here
strcpy(name, x.c_str());
}
main.cpp main.cpp
int main(){
myClass *classArr;
int amountRecord = getRecord(); //check the number of record and return it(assuming it return 5)
classArr = new myClass[amountRecord];
loadClassData("test.dat",classArr);
}
void loadClassData(string filename,myClass *classArr){
ifstream ins(filename,ios::in);
int counter = 0;
string className;
string temp;
if(ins.good()){
while(!ins.eof()){
className = "";
getline(ins, className,'\n');
classArr[counter].setName(className);
counter++;
}
ins.close();
}
The problem is in how you loop when reading (see Why is “while ( !feof (file) )” always wrong? for why). 问题在于您在阅读时如何循环播放(请参阅“ 为什么while(!feof(file))”总是错误的? )。
This causes the loop to iterate one extra time leading you to use an out-of-bounds index into the classArr
array, which leads to undefined behavior and the crash. 这将导致循环重复一个额外的时间,导致您在
classArr
数组中使用越界索引,从而导致未定义的行为和崩溃。
Instead do eg while (std::getline(ins, className))
而是做
while (std::getline(ins, className))
In function void myClass::setName(string x)
you are using some variable called sName
. 在
void myClass::setName(string x)
函数中,您使用了一个名为sName
变量。
I have no idea where it's declared, but you should be using the variable x
that is passed in the function. 我不知道它在哪里声明,但是您应该使用在函数中传递的变量
x
。
Where sName is come from? sName来自哪里? I think it should be like this.
我认为应该是这样。
myStudent::myStudent(){}
void myStudent::setName(string x){
name = new char[x.length()+1]; //my xcode give me signal SIGBART here
strcpy(name, x.c_str());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.