I’m trying code a simple homework at school and get the error Segmentation fault (core dumped) implementing a linked list in C++ in this way:
struct Word{
string word;
string meaning;
Word * next;
};
struct dictionary{
Word *head = NULL;
int count;
}dict;
string addWord(string word, string meaning){
Word *newWord = new Word;
newWord -> word = word;
newWord -> meaning = meaning;
newWord -> next = dict.head;
dict.head = newWord;
dict.count++;
}
I’m trying to add a word (node) when get the error, I can’t use c++ class because is a requieriment of a teacher, sincery thank for you help!
dict.countis never initialized. Given that your compiler can include default initializations in astructdefinition, you should writeint count = 0;where it is defined. This is not causing your segfault, probably, but you still need to fix it.I suspect
addWordfailing to return astring, despite it having that as a return value, could be causing your segfault. This results in undefined behavior (which could crash). A compiler worth its salt would give you a fatal warning for writing the code you wrote. Change the return type ofaddWordtovoid. Like this:General advice about posting problems on this website:
When you post problems, include everything that it needs for your code to compile and run, including a
mainmethod. Remove anything you don’t think is important from your code, but what you leave behind should still run, and should demonstrate your problem.When you show code that is incomplete, you are being a fool: if you knew what was important, you wouldn’t need to ask for help, would you? So you need to post complete code.
When you show too much code, you are being impolite. First pare your code down to the minimal example that shows your problem, but leave it complete so we can see where your real problem is.