字符串赋值中的c ++分段错误

时间:2015-04-13 03:50:25

标签: c++ malloc new-operator stdstring

需要帮助以了解下面的字符串分配如何导致过程中的分段错误。请注意,它是非常随机的,相同的数据集有时会提供核心转储,有时则不会。 处理多个文件时会出现故障。处理单个文件时没有失败。 处理流程是 - 读取输入文件(某种格式) - 每条记录处理 - 准备输出文件(新格式)

我验证了代码处理的输入数据很好 - 对于它失败的实例。 因此,看起来代码中的某些分配/赋值可能导致核心转储(分段错误)

请建议。感谢。

代码如下所示:

class RecordHolder
{
public:
    RecordHolder();
    ~RecordHolder(){}
    bool init();
    void setRecordType(char i_recordType)           { m_recordType = i_recordType; }
    **void setSomeID(string i_someID)           { m_someID = i_someID.c_str(); }**
private:
    char   m_recordType;
    string m_someID;
};

bool RecordHolder::init() { m_recordType = NULL;    m_someID = "";  return true; }

int SomeClass::parseRecord(const char* i_rec)
{
    char* pToken;
    int tokenCounter;
    char str[RECORD_SIZE];

    strcpy(str,i_rec);
    pToken = strtok(str, RECORD_FIELDS_DELIMETER);
    if (!pToken) 
    {
        return -1;
    }
    m_currRecord->init(); // init the m_currRecord before parsing the record
    tokenCounter = 0;
    while( (pToken != NULL) || (tokenCounter < NUMBER_OF_FILEDS) )
    {
        tokenCounter++;
        if (pToken)
            switch(tokenCounter)
            {
                case 1:
                    m_currRecord->setRecordType(*pToken);
                    break;
                case 2:
                    **//Process crashes with SEGMENTATION FAULT here randomly**
                    m_currRecord->setsomeID(pToken);
                    break;
                default:
                    break;
            } // End of switch section.
        pToken = strtok(NULL, RECORD_FIELDS_DELIMETER);
    } //  End of while loop
}

来自dbx工具(solaris系统)的核心转储堆栈位于

之下
current thread: t@1
  [1] realfree(0x1008d85d0, 0xffffffff76db6f78, 0xffffffff7ffe8daf, 0xad, 0x100067024, 0x1001cf450), at 0xffffffff76c4f5e0
  [2] cleanfree(0x0, 0x1008d8c30, 0x60, 0x0, 0x0, 0x0), at 0xffffffff76c4fedc
  [3] _malloc_unlocked(0x3b, 0x0, 0x0, 0x2, 0x2, 0x1), at 0xffffffff76c4efbc
  [4] malloc(0x3b, 0xff000000, 0x0, 0x0, 0xfffffc00, 0xffffffff), at 0xffffffff76c4ee94
  [5] operator new(0x3b, 0x0, 0x0, 0x1, 0x1, 0x400), at 0xffffffff795ef2e4
  [6] std::basic_string<char,std::char_traits<char>,std::allocator<char> >::__getRep(0xffffffff7ffe7cb0, 0x9, 0x9, 0x123a54, 0x81010100, 0xff00), at 0xffffffff7ae761ec
  [7] std::basic_string<char,std::char_traits<char>,std::allocator<char> >::basic_string(0xffffffff7ffe7cb0, 0xffffffff7ffe7d1e, 0xffffffff7ffe7caf, 0x3030303030300a, 0x100067024, 0x1001cf450), at 0xffffffff7ae70844
=>[8] SomeClass::parseRecord(this = 0xffffffff7ffe9448, i_rec = 0xffffffff7ffe86b3 "D|088888888|601251194|........|K                   |00000.000000\n"), line 492 in "SomeClass.cpp"
  [9] SomeClass::processSorted(this = 0xffffffff7ffe9448), line 632 in "SomeClass.cpp"
  [10] SomeClass::processFile(this = 0xffffffff7ffe9448), line 210 in "SomeClass.cpp"

1 个答案:

答案 0 :(得分:-2)

一个潜在的原因可能是strcpy(str,i_rec)。使用strncpy而不是strcpy是一个好习惯。