使用strcpy时构造函数中的分段错误

时间:2014-03-04 15:32:35

标签: c++

大家好我正在编写一个程序,读取大学任务的NMEA句子,我遇到了分段错误的问题。有人可以帮我解决吗?

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];
}

错误似乎发生在strcpy。我做错了什么?

3 个答案:

答案 0 :(得分:2)

您没有为c_sent分配内存。这是未定义的行为。

使用char *c_sent = new char[sentence.size() + 1];。我为null终结符添加了空间。不要忘记在函数退出之前调用delete[] c_sent;

(顺便说一下,tempsentence的生命周期内有效,除非它以任何方式进行了修改。)。

答案 1 :(得分:0)

临时字符串c_sent未初始化。

char * c_sent

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

在退出之前不要忘记自由。

free(c_sent);

你不需要这种方式。

答案 2 :(得分:0)

成员函数有几个缺陷。

如果函数的参数没有改变,那么最好将函数声明为

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

正如已经说过的那样,你没有在你要复制句子的地方分配记忆。指针c_sent未由分配的内存的地址初始化。

第二个缺陷是pch总是指向c_sent中的相同地址,因为你错误地使用了函数strtok。你应该按照以下方式使用它

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

还不清楚如何确定字符串包含的部分数量。