为什么我会出现分段故障(线路丢弃)?

时间:2013-09-27 15:53:30

标签: c arrays pointers segmentation-fault

在用户输入他们的名字和姓后,我需要程序做多件事情都很好,除了我需要编程以相反的顺序打印他们的名字(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);

}

2 个答案:

答案 0 :(得分:3)

当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"

修改

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

// 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"

答案 1 :(得分:1)

更常见的方法是找出您获得segfault的行,使用gcc标记(例如-g)使用gcc -g file.c编译您的程序,然后运行{{1 (例如gdb')然后键入gdb a.out然后run它应该给你segfault的行(或任何类型的错误)及其背后的原因