首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >为什么分段错误(核心转储)错误适用于我的C程序?

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

Stack Overflow用户
提问于 2012-10-02 14:41:07
回答 3查看 667关注 0票数 0

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

代码语言:javascript
代码运行次数:0
运行
复制
#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;
}

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

代码语言:javascript
代码运行次数:0
运行
复制
Hello!
Today
is 
a
beautiful 
day!!
EN

回答 3

Stack Overflow用户

发布于 2012-10-02 14:46:47

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

代码语言:javascript
代码运行次数:0
运行
复制
str[nextindex]='\0'

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

代码语言:javascript
代码运行次数:0
运行
复制
char *str = "Hello! Today is a beautiful day!!\t\n";
int i = nextword(str);

由于"Hello! Today is a beautiful day!!\t\n"是字符串文字更改,它是未定义的行为,在您的示例中(幸运的是)它导致了seg-fault。

票数 5
EN

Stack Overflow用户

发布于 2012-10-02 14:45:21

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

然后,您应该学习如何使用调试器(即Linux上的gdb ),可能还会使用像valgrind这样的泄漏检测器。

如果你取消引用一些“坏的”指针,例如一个空指针或一个未初始化的指针,就可能发生segmentation fault。如果你写到一个只读段中,也可能会发生这种情况(你可能正在覆盖一个字符串文字,它被放入一个称为.text.rodata- -so的只读段中)。

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

票数 4
EN

Stack Overflow用户

发布于 2012-10-02 14:49:13

请给nextindex一个初始值

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12685600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档