所以我的代码中出现了段错误,我似乎无法弄清楚是什么原因造成的。有没有人能够捕捉到我没有捕捉到的东西?
从逻辑上讲,我试图通过将事物连接到末尾来创建一个 char 数组(一个字符串),然后将其添加到一个字符串数组中。
它最终应该是这样的'word1,word2,word3,word4,word5 ...等'
段故障发生在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 堆栈跟踪:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004013d1 in save_ladder (curNode=0x6420f0) at wordladder.c:150
150 strcat(str, ", ");
有谁知道为什么会发生这种情况?