Paul Ang
Paul Ang

Reputation: 65

Dynamic memory allocation error

I have a char pointer as a private member of a class. 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. 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 a breakpoint in malloc_error_break to debug error

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:

class myClass{
private:
char *name;
public:
  myClass();
  void setName(string);
}

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

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();
}

Upvotes: 0

Views: 200

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409176

The problem is in how you loop when reading (see Why is “while ( !feof (file) )” always wrong? for why).

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.

Instead do e.g. while (std::getline(ins, className))

Upvotes: 1

okan
okan

Reputation: 1

Where sName is come from? 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());
}

Upvotes: 0

Yochai Timmer
Yochai Timmer

Reputation: 49251

In function void myClass::setName(string x) you are using some variable called sName.

I have no idea where it's declared, but you should be using the variable x that is passed in the function.

Upvotes: 0

Related Questions