4 Replies - 3773 Views - Last Post: 18 March 2013 - 08:08 AM Rate Topic: -----

#1 KorvusKoraks  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 02-August 11

Segmentation fault when trying to convert string to char array

Posted 17 March 2013 - 12:58 PM

Okay, so this is a homework assignment. I've been stuck with a pretty annoying problem.

I've cut out non-relevant parts of the code. The type of "id" is const std::string&.

Person Person::add(Person *p)
{
   std::string test = p->getId();
   char id1[11];
   strcpy(id1, test.c_str()); // the crash happens at this point
}


So what am I doing wrong? This works well ("people" is a vector):

char id2[11];
strcpy(id2, people[i].getId().c_str());



Is This A Good Question/Topic? 0
  • +

Replies To: Segmentation fault when trying to convert string to char array

#2 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5846
  • View blog
  • Posts: 12,705
  • Joined: 16-October 07

Re: Segmentation fault when trying to convert string to char array

Posted 17 March 2013 - 04:07 PM

test.c_str() would have to be a length of 10 or less. Larger than that and you go boom. Why would you want to convert to a c-string in the first place?
Was This Post Helpful? 0
  • +
  • -

#3 KorvusKoraks  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 02-August 11

Re: Segmentation fault when trying to convert string to char array

Posted 17 March 2013 - 04:23 PM

Thanks for the answer, that was the problem (the arrays were too small).

I was having some trouble comparing the strings together and tried to do it "the hard way" as one solution.
Was This Post Helpful? 0
  • +
  • -

#4 jimblumberg  Icon User is offline

  • member icon


Reputation: 4098
  • View blog
  • Posts: 12,682
  • Joined: 25-December 09

Re: Segmentation fault when trying to convert string to char array

Posted 17 March 2013 - 08:41 PM

Why don't you post your attempt at comparing std::strings? Maybe we can show you what you're doing wrong with the strings, it should be much easier to compare strings.

Jim
Was This Post Helpful? 0
  • +
  • -

#5 KorvusKoraks  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 02-August 11

Re: Segmentation fault when trying to convert string to char array

Posted 18 March 2013 - 08:08 AM

I actually had forgotten a whole else block from the code... that's why it didn't work. So it had nothing to do with the strings after all. :D

But thanks for the answers, anyway.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1