C、 获取分段错误
我有一个名为islands.txt的文件,其中包含以下内容:C、 获取分段错误,c,segmentation-fault,C,Segmentation Fault,我有一个名为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(isla
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] != '\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);
}
相反,我得到的只是分割错误。我什么都试过了,但还是卡住了。我从哪里得到了分割错误?我是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是匹配的调试器。您可以简单地通过添加诸如
printf(“执行行%d\n”,\uu行\uuu)之类的语句进行调试代码>随处可见,以查看执行的内容和未执行的内容。但最好学会使用调试器。使用调试器,逐步检查变量,直到得到segfault,它应该给你一个线索island*previousIsland代码>-->孤岛*previousIsland=NULL
和if(previousIsland){…}
-->newIsland->previousIsland=previousIsland代码>@KorayTugay未设置;使用未初始化的变量会导致未定义的行为。@KorayTugay可能会导致段错误,因为未显式初始化为NULL。感谢您的输入。我使用OSX和eclipse,但仅用于输入,我使用gcc hello.c从终端编译,只需按./a.out打印,我还将研究调试。
island *previousIsland;
while(fscanf(islandsFile,"%s",name) != EOF){
/* some code omitted */
if(previousIsland){
newIsland->previous = previousIsland;
}