Hi all, I have some problems with my program, as it always compiles with segmentation fault after it run finishes. ANy help is appreciated

Program received signal SIGSEGV, Segmentation fault.
0x00375d37 in ?? () from /lib/tls/i686/cmov/libc.so.6
(gdb) bt
#0  0x00375d37 in ?? () from /lib/tls/i686/cmov/libc.so.6
#1  0x0804992b in Chord::isValid(char*) ()
#2  0x0804965b in Chord::Read(std::string) ()
#3  0x080491e7 in main ()

and the codes involved

void Chord::Read(string filename) {

    string line;
    ifstream inFile;
    inFile.open(filename.c_str());
    if (inFile.fail()) {
        cout << "File not exists" << endl;
        exit(1);
    }

    while (inFile.good()) {
        getline(inFile, line); //read instruction line by line
        //process instruction, first extract the command
        char *inst = strtok(&line[0], " "); //command
        int num, num2;
        string data;
        if (isValid(inst)) 
       {
            //process valid instruction
            if (strcmp(inst, "insert") == 0) 
            {
                num = atoi(strtok(NULL, " ")); //extract peer number
                data = strtok(NULL, "\0");
                //cout << data << endl;
            } 
            else 
            {
                num = atoi(strtok(NULL, " ")); //extract peer number
                //if (strcmp(inst, "find") == 0)
                  //  num2 = atoi(strtok(NULL, " ")); //extract key
            }
        } else
        continue; //skip invalid instruction
bool Chord::isValid(char *inst) {

    if (strcmp(inst, "init") == 0
            || strcmp(inst, "addpeer") == 0
            || strcmp(inst, "removepeer") == 0
            || strcmp(inst, "insert") == 0
            || strcmp(inst, "print") == 0)
        return true;
    return false;
}

Recommended Answers

All 3 Replies

I'm not as familiar with strtok, but you should try passing in line.c_str() to it instead of the address of the first character on line 14. What you did assumes something about the implementation of the std::string which may not be true.

Either way, you seem to be getting a null pointer being passed into isValid. Output the value of inst after line 14 to see what's in there.

The strtok function:
"A null pointer is returned if there are no tokens left to retrieve."

You should handle that case. Possibly in your isValid() function (like a test for NULL before all the strcmp calls).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.