0

Hi guys I'm writing a program that reads NMEA sentences for a university assignment and I'm having trouble with segmentation fault. Can anyone help me fix it, please?

NmeaSentence::NmeaSentence(std::string sentence) {
    const char *temp = sentence.c_str();
    char *c_sent;
    strcpy(c_sent, temp);
    char *pch;
    for(int i = 0; i < MAX_SENTENCE_PARTS; i++){
        pch = strtok(c_sent, ",");
        this->sentenceParts[i] = pch;
    }
    this->sentence = sentence;
    this->sentenceType = sentenceParts[0];
}

The error seems to be happening at strcpy. What am I doing wrong?

Will
  • 123
  • 1
  • 1
  • 7

3 Answers3

2

You don't allocate memory for c_sent. That's undefined behaviour.

Use char *c_sent = new char[sentence.size() + 1];. I've added space for the null terminator. Don't forget to call delete[] c_sent; before the function exits.

(By the way, temp is valid for the lifetime of sentence, unless it's modified in any way.).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

The temporary string c_sent is uninitialized.

char * c_sent

to

char * c_sent = strdup(sentence.c_str());

Dont forget to free, before exit.

free(c_sent);

You won't need temp this way.

Sanjaya R
  • 6,246
  • 2
  • 17
  • 19
0

The member function has several defects.

If the parameter of the function is not changed then it would be better to declare the function as

NmeaSentence::NmeaSentence( const std::string & sentence);

As it was already said you did not allocate memory where you are going to copy sentence. Pointer c_sent was not initialized by the address of an allocated memory.

The second defect is that pch always points to the same address in c_sent because you are incorrectly using function strtok. You should use it the following way

char *pch = strtok(c_sent, ",");
for(int i = 0; i < MAX_SENTENCE_PARTS && pch; i++){
    this->sentenceParts[i] = pch;
    pch = strtok( NULL, ",");
}

Also it is not clear how you will determine how many parts the string contains.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335