C, Getting segmentation fault -
i have file called islands.txt contents:
islandone islandtwo islandthree
and code:
#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(){ // file read. file *islandsfile = fopen("islands.txt","r"); // temporary location store name read file. char name[40]; // temporary pointer island has been read linking. island *previousisland; while(fscanf(islandsfile,"%s",name) != eof){ // allocate space new island , point (*newisland) pointer island *newisland =malloc(sizeof(island)); // assign name newisland->name = name; // if previousisland pointer not null // means there island read before newisland in file if(previousisland){ // newisland.previous should hold address of read island.. newisland->previous = previousisland; } // previousisland newisland.. previousisland = newisland; printisland(*newisland); puts(""); } fclose(islandsfile); }
my expectation of output is:
islandone islandtwoislandone islandthreeislandtwo
instead getting segmentation fault. have tried stuck. getting segmentation fault here? pretty new c , have no idea how debug.
yes need allocate memory name well. allocate structure
typedef struct island{ char *name; struct island *previous; } island;
so this
// assign name newisland->name = name;
will set pointer array have on stack, every loop iteration same address.
instead like
newisland->name = strdup(name);
or if prefer
newisland->name = malloc( strlen( name ) + 1 ); strcpy( newisland->name, name );
Comments
Post a Comment