C、 正在获取分段错误



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

islandone
islandtwo
islandthree

这是我的代码:

#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] != ''){
        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);
}

我对输出的期望是:

islandone
islandtwoislandone
islandthreeislandtwo

相反,我得到的只是分割错误。我什么都试过了,但我被卡住了。这里的分段错误在哪里?我对C还很陌生,不知道如何调试。

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

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

所以这个

// assign name
newIsland->name = name;

将指针设置到堆栈上的数组,但每次循环迭代时,指针都是相同的地址。

而是做一些类似的事情

newIsland->name = strdup(name);

或者如果你更喜欢

newIsland->name = malloc( strlen( name ) + 1 );
strcpy( newIsland->name, name );

这里有几个问题。除了CyberSpock提到的代码外,您还有以下代码:

island *previousIsland; 
while(fscanf(islandsFile,"%s",name) != EOF){
   /* some code omitted */
   if(previousIsland){
        newIsland->previous = previousIsland;
   }

previousIsland变量未初始化,第一次if可能为true,因此前一个指针指向无效内存。然后,当您在printIsland中到达末尾时,它将继续跟随未初始化的指针,进入无效内存。我也看到你没有释放()任何内存,但这可能是因为你不喜欢这样一个小例子。

要调试C程序,调试器就是你的朋友。现在您不知道使用哪种操作系统和编译器,但如果使用gcc,gdb就是匹配的调试器。

相关内容

  • 没有找到相关文章

最新更新