[英]Why does segmentation fault (core dumped) error apply to my C program?
I keep getting this error and I am not sure how it applies to my program. 我一直收到此错误,并且不确定如何将其应用于我的程序。 This is my program.
这是我的程序。
#include<stdio.h>
#include<stdlib.h>
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;
}
My program is supposed to have an output to the console of 我的程序应该在控制台输出
Hello!
Today
is
a
beautiful
day!!
You are trying to change a String literal . 您正在尝试更改String文字 。 This results in undefined behavior, such as a segfault.
这会导致未定义的行为,例如段错误。
str[nextindex]='\0'
and in Here, str
is the parameter of nextWord()
, which is: 在这里,
str
是nextWord()
的参数,即:
char *str = "Hello! Today is a beautiful day!!\t\n";
int i = nextword(str);
Since "Hello! Today is a beautiful day!!\\t\\n"
is a string literal - changing it is udnefined behavior, and in your case (luckily) it caused a seg-fault. 由于
"Hello! Today is a beautiful day!!\\t\\n"
是字符串文字,因此更改它是未定义的行为,就您而言(幸运的是)它导致了段错误。
You should compile with all warnings and debugging info enabled (if using GCC eg on Linux, that means compiling with gcc -Wall -g
). 您应该在所有警告和调试信息启用的情况下进行编译 (如果在Linux上使用GCC ,则意味着使用
gcc -Wall -g
编译)。
Then you should learn how to use the debugger (ie gdb
on Linux) and possibly a leak detector like valgrind 然后,您应该学习如何使用调试器(即Linux上的
gdb
)以及可能的泄漏检测器(如valgrind)
a segmentation fault may happen if you dereference some "bad" pointer, eg a NULL one or an uninitialized one. 如果取消引用某些“坏”指针(例如NULL指针或未初始化的指针),则可能会发生分段错误 。 It also may happen if you write into a read-only segment (you are probably overwriting a string literal which is put into a read-only -so called
.text
or .rodata
- segment) 它如果写入只读段也可能发生(你可能改写一个字符串文字被放到一个只读-所以所谓
.text
或.rodata
-段)
Taking account of every warning of the compiler (and enabling them) and using a debugger are essential skills of any C programmer. 考虑到对编译器的所有警告(并启用它们)并使用调试器是任何C程序员的基本技能。
请给nextindex
一个初始值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.