So I’m getting a seg fault in my code, and I just can’t seem to figure out what is causing it. Is anyone able to catch something that I was not?
Logically I’m trying to create a char array (a string) by concatenating things on to the end, and then add it to an array of strings.
what it should end up looking like is this ‘word1, word2, word3, word4, word5… etc’
The seg fault happens on strcat(str, ", ");
void save_ladder(graphNode *curNode) {
char *str = malloc(1000 * sizeof(char));
strcpy(str, "");
strcat(str, curNode->word);
strcat(str, ", ");
graphNode *prev = curNode->prevWord;
while (prev != NULL) {
if (prev->prevWord != NULL) {
strcat(str, prev->word);
strcat(str, ", "); // SEG FAULT HAPPENS HERE
}
else
strcat(str, prev->word);
prev = prev->prevWord;
}
ladders[numLadders++] = str;
}
gdb stacktrace:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004013d1 in save_ladder (curNode=0x6420f0) at wordladder.c:150
150 strcat(str, ", ");
Does anyone know why this might be happening?
Probably a buffer overflow. Put the following code just inside your
whileloop and check if that’s the case:If the sum of those two numbers gets anywhere near 1000, your buffer will probably need to be bigger.
Alternatively, if the second ever seems to be a little large or there appear to be way too many words, then either the data in your list, or the list structure itself is suspect.
In addition, there are two other points. The first is that you never need to multiply by
sizeof(char)since that is always 1 (you should also check the return value ofmallocas well, in case it fails).The second is that you can simplify your string construction thus, without the
ifstatement within thewhile: