1

Have a look at this code: I am trying to read in a number of strings from the console and store them in a dynamic array.

int Doctor::addPatients()
{
  string* names = NULL;
  int num;
  cout << "how many patients are to be added? ";
  cin >> num;
  numPatients=num;
  names = new string[numPatients];
  for(int i=0;i++;i<numPatients){
    cout << "enter the next patient's name: ";
    cin.clear();
    cin >> names[i];
  }
  patients = names; //patients is a private member variable of class Doctor
}

When I execute this code, I get the following error:

malloc: *** error for object 0x10c100898: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

Any help is greatly appreciated

1
  • 1
    Stop using pointers, change to std::vector instead. Commented Oct 3, 2012 at 13:26

3 Answers 3

3
for(int i=0;i++;i<numPatients)  // Condition is the second expression in for syntax

Wrong syntax.

for(int i=0;i<numPatients; i++)

What compiler are you using ? You should get a compilation error than a run-time error. Also did you write a copy constructor ? For more info see Rule of Three. To ease the job, use std::vector<std::string>.

Sign up to request clarification or add additional context in comments.

1 Comment

Man I really messed up that for loop. Thank you. One of those things I didn't even think about looking at again (after fixing the first problem). I'm using g++ on Mac OSX, Xcode 4.4.1, no flags except for -g when debugging.
3

you do not initialize the integer i

2 Comments

For example: std::shared_ptr<std::string> s(new std::string());
Using shared pointers sounds like a good idea. That said, I'd still like to know the problem with the code as written.
1

In the for statement, for(int i;i++;i<numPatients)

i should be initialised to 0 and condition should be the second parameter Correct format should be -

for(int i=0;i<numPatients;i++)

cin is not good method to get the string input. cin reads only till it sees space character (space,newline,tab..) Alternatively use getline function -

syntax:

getline(cin,names[i])

1 Comment

Formatting wasn't good enough and stripped out the explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.