【问题标题】:Why am I getting segmentation fault (cord dumped)?为什么会出现分段错误(掉线)?
【发布时间】:2013-09-27 15:53:29
【问题描述】:

在让用户输入他们的名字和姓氏后,我需要程序执行多项操作,这些操作都可以正常工作,只是我需要编程以相反的顺序打印他们的姓名(John Doe = Doe John)。由于我从你们那里得到了帮助,我认为我在它们中具有适当的功能,但是我仍然遇到分段错误。这里有什么问题。

这是程序中的最后一个函数

#include <stdio.h>
#include <string.h>

int main ()
{
    printf("Enter your first and last name\n");

    char name [25]={'\0'};
    char * space;

    fgets(name,sizeof(name),stdin);

    printf("You Entered: %s     \n", name);

    printf("There are %u characters in your name including the space. \n", strlen(name));

    char end;
    int i;
    end = strlen(name) -1;
    printf("Your name backwards is");
    for (i = end; i >= 0; --i)
    {
        printf("%c", name [i]);
    }

    printf("\nLooking for the space in your name \n", name);
    space=strchr(name, ' ');
    while (space!=NULL)
    {
        printf("The space was found at character %d\n", space-name+1);
        space=strchr(space+1, ' ');
    }
    //Why am I getting a segmentation fault (cord dumped) error here?
    *space = '\0';
    printf(" %s %s ", space+1, name);

}

【问题讨论】:

  • 你一遍又一遍地发布同样的问题,例如最近你发布了here你在那里得到了合理的答案。请努力理解。

标签: c arrays pointers segmentation-fault


【解决方案1】:

当 while 循环中断 space 为 NULL 时,您正在写入 NULL 地址。

while (space!=NULL) <-- "loop breaks when space is NULL"
{
    printf("The space was found at character %d\n", space-name+1);
    space=strchr(space+1, ' ');
}
//Why am I getting a segmentation fault (cord dumped) error here? 
*space = '\0';  <--- "space is NULL"

编辑:

要以相反的顺序打印输入的单词,请尝试以下代码(阅读 cmets 以了解):

// suppose name is "Grijesh    Chauhan"
char *last = NULL, *firstspcae = NULL; 
firstspcae = space = strchr(name, ' ');
*firstspcae = '\0';  // At first space insert nul char '\0'
while (space != NULL)
{
    printf("The space was found at character %d\n", space-name+1);
    last = space + 1;  //next to space 
    space=strchr(space + 1, ' ');
}
printf("\n%s %s ", last, name);   // "Chauhan Grijesh"
*firstspcae = ' ';  // recover your original  string back 
printf("\n%s %s ", last, name);  // "Grijesh    Chauhan"

【讨论】:

  • 那你建议我怎么做?我需要帮助,显然我只是一个初学者,所以任何你可以给我的例子让我从中学习都会很棒。
  • @GrijeshChauhan 它在问题中。他试图取一个正确的名字并翻转单词,而不是字母。
  • @GrijeshChauhan 我不知道现在该尝试什么,遗憾的是,我已经为这个程序工作了几个小时。我正在寻找你们帮助解决我的问题。
  • @user2172993 等等,让我读一下……你想要吗?如果我输入"Grijesh Chauhan" 最后一行的输出是"Chauhan Grijesh"
  • 是的,这正是我需要发生的事情
【解决方案2】:

一种更通用的方法来找出你在哪一行得到你的 segfault ,用gcc编译你的程序,使用-g标志(例如gcc -g file.c)然后运行gdb'(例如gdb a.out)然后输入run 然后输入where 它应该给你segfault的行(或任何排序错误)及其背后的原因

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 2018-01-07
    相关资源
    最近更新 更多