为什么分段错误(核心转储)错误适用于我的C程序?

我一直收到这个错误,我不确定它是如何适用于我的程序的。 这是我的计划。

#include #include int nextword(char *str); void main(void) { char *str = "Hello! Today is a beautiful day!!\t\n"; int i = nextword(str); while(i != -1) { printf("%s\n",&(str[i])); i = nextword(NULL); } } int nextword(char *str) { // create two static variables - these stay around across calls static char *s; static int nextindex; int thisindex; // reset the static variables if (str != NULL) { s = str; thisindex = 0; // TODO: advance this index past any leading spaces while (s[thisindex]=='\n' || s[thisindex]=='\t' || s[thisindex]==' ' ) thisindex++; } else { // set the return value to be the nextindex thisindex = nextindex; } // if we aren't done with the string... if (thisindex != -1) { nextindex = thisindex; // TODO: two things // 1: place a '\0' after the current word // 2: advance nextindex to the beginning // of the next word while (s[nextindex] != ' ' || s[nextindex] != '\n' || s[nextindex] != '\t') { if ( s[nextindex] == '\0') return -1; else { nextindex++; if (s[nextindex]==' '||s[nextindex]=='\n'||s[nextindex]=='\t') str[nextindex]='\0'; } } } return thisindex; } 

我的程序应该有一个输出到控制台

 Hello! Today is a beautiful day!! 

您正在尝试更改字符串文字 。 这会导致未定义的行为,例如段错误。

 str[nextindex]='\0' 

在这里, strnextWord()的参数,它是:

 char *str = "Hello! Today is a beautiful day!!\t\n"; int i = nextword(str); 

因为"Hello! Today is a beautiful day!!\t\n"是一个字符串文字 – 改变它是udnefined行为,在你的情况下(幸运的是)它导致了一个seg-fault。

您应该编译时启用所有警告和调试信息(如果在Linux上使用GCC ,这意味着使用gcc -Wall -g编译)。

然后你应该学习如何使用调试器(即Linux上的gdb )以及可能的valgrind等泄漏检测器

如果您取消引用某些“坏”指针(例如NULL指针或未初始化指针),则可能会发生分段错误 。 如果你写入只读段也可能发生(你可能会覆盖一个字符串文字,它被放入只读 – 也称为.text.rodata – segment)

考虑编译器的每个警告(并启用它们)和使用调试器是任何C程序员的基本技能。

请给nextindex一个初始值