C,获取分段错误

Kor*_*gay 0 c segmentation-fault

我有一个名为islands.txt的文件,内容如下:

islandone
islandtwo
islandthree
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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

typedef struct island{
    char *name;
    struct island *previous;
} island;

void printIsland(island is){
    printf("%s", is.name);
    if(is.previous && is.previous->name[0] != '\0'){
        printf("%s", is.previous->name);
    }
}

int main(){

    // the file to be read.
    FILE *islandsFile = fopen("islands.txt","r");

    // temporary location to store the name read from the file.
    char name[40];

    // temporary pointer to an island which has been already read for linking.
    island *previousIsland;

    while(fscanf(islandsFile,"%s",name) != EOF){
        // allocate space for a new island and point to it with (*newIsland) pointer
        island *newIsland =malloc(sizeof(island));

        // assign name
        newIsland->name = name;

        // if previousIsland pointer is not null
        // it means there is an island that was read before newIsland in the file

        if(previousIsland){
            // newIsland.previous should hold the address of this previously read island..
            newIsland->previous = previousIsland;
        }
        // now previousIsland is the newIsland..
        previousIsland = newIsland;
        printIsland(*newIsland);
        puts("");
    }

    fclose(islandsFile);
}
Run Code Online (Sandbox Code Playgroud)

我对输出的期望是:

islandone
islandtwoislandone
islandthreeislandtwo
Run Code Online (Sandbox Code Playgroud)

相反,我得到的只是分段错误.我已经尝试了一切,但我被卡住了.我在哪里得到分段错误?我是C的新手,我不知道如何调试.

And*_*rsK 5

是的,您还需要为名称分配内存.您只为结构分配

typedef struct island{
    char *name;
    struct island *previous;
} island;
Run Code Online (Sandbox Code Playgroud)

所以这

// assign name
newIsland->name = name;
Run Code Online (Sandbox Code Playgroud)

将指针指向您在堆栈上的数组,但是每次循环迭代它都将是相同的地址.

而是做类似的事情

newIsland->name = strdup(name);
Run Code Online (Sandbox Code Playgroud)

或者如果你愿意的话

newIsland->name = malloc( strlen( name ) + 1 );
strcpy( newIsland->name, name );
Run Code Online (Sandbox Code Playgroud)