Search code examples
c++pointerslinked-listcoredumpbus-error

Bus error (core dumped) with Linked Lists?


I'm writing a program that allows a user to type in a file name of a person database to be read; the program then creates a linked list of state objects and a linked list of person objects within each state link to organize the information from the file.

I know the linked list part works because I was able to directly code in the file name and print out the list of states and the list of people in each state; however, when I try to allow the user to type in the file name as a command, I'm getting a Bus error. When I run the code in gdb, all it tells me is:

Program received signal SIGBUS, Bus error.
0x280df0bd in std::operator>><char, std::char_traits<char> > ()
   from /usr/lib/libstdc++.so.5

I don't even get a line number to go off of! Any help would be super appreciated. Here's the command and read portions of my code:

List<State*>* read(char* filename) {
    string fname, lname, birthday, state;
    int ssn;
    List<State*>* state_list = new List<State*>();

    ifstream file(filename);
    if (file.fail()) {
        cerr << "Error reading file.\n";
        exit(1);
    }

    while (!file.eof()) {
        file >> birthday >> ssn >> fname >> lname >> state;
        Link<State*>* searchres = searchList(state, state_list);
        Person* p = new Person(fname, lname, ssn, birthday, state);
        if (searchres == NULL) // create new state
        {
            State* addedstate = state_list->addLink(new State(state))->data;
            addedstate->res_list.addLink(p);
        }

        else // add to pre-existing state
        {
            searchres->data->res_list.addLink(p);
        }
    }
    return state_list;
}

void main() {
    string cmd;
    cout << "Type your command in all lowercase letters.\n";
    cin >> cmd;
    if (cmd == "read") {
        char* filnm;
        cin >> filnm;
        List<State*>* state_ls = read(filnm);
        Link<Person*>* counter = state_ls->first->data->res_list.first;
        while (counter != NULL) {
            cout << counter->data->ssn << "\n";
            counter = counter->next;
        }
    }
}

Solution

  • Right away, you have a problem:

    char* filnm;
    cin >> filnm;
    

    The pointer is uninitialized, yet you read in information using that pointer.

    Either use std::string, or a char array that is appropriately sized.

    To use a std::string in the open of the file:

    std::string filnm;
    cin >> filnm;
    read(filnm.c_str());
    

    Your read function should also change the parameter to const char* instead of char *. You are not changing the contents of the character array being passed, so it should be const.

    Edit: You actually do not need to use c_str(), as the std::string has a constructor that takes a const char*. Still, change the parameter to const char *filename in the read() function.