我使用以下命令进行编译:(gcc -Wall -lm -std=c11 *.c -o showList
我还有其他c文件),运行时出现分段错误./showList
。
但是,如果我使用以下命令进行编译,则该列表显示正常且没有段错误: dcc -Wall -lm -std=c11 *.c -o showList
我是C的新手,这确实使我感到困惑,任何帮助或建议都将不胜感激!
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <err.h>
#include <sysexits.h>
#include <math.h>
typedef struct ListNode *List;
typedef struct ListNode {
char *data;
struct ListNode *next;
}ListNode;
List getListFromFile(void);
void showList (List L);
List listInsert (List L, char *word);
int main (int argc, char **argv){
List list = getListFromFile();
showList(list); //seg fault here?
}
List getListFromFile(void) {
List newList = NULL;
FILE *txtFile;
txtFile = fopen("someRandom.txt", "r"); // word1 word2 word3 word4
if(txtFile == NULL){
fprintf(stderr,"Error opening txt\n");
return NULL;
}
char word[100];
while(fscanf(txtFile, "%s", word) != EOF){ //read from txt file and store words into list
printf("%s ", word); // testing
newList = listInsert(newList, word);
}
fclose(txtFile);
return newList;
}
void showList (List L){
if (L == NULL) return;
while (L != NULL) {
printf("%s ", L->data);
L = L->next;
}
printf("\n");
}
static ListNode *newListNode (char *word) {
ListNode *n = malloc (sizeof (*n));
if (n == NULL) err (EX_OSERR, "err creating node \n");
n->data = strdup (word);
n->next = NULL;
return n;
}
List listInsert (List L, char *word){ //insert at head
ListNode *n = newListNode(word);
if (L == NULL) {
return n;
} else {
n->next = L;
return n;
}
}
首先,您的程序存在gcc在提供的屏幕截图中诊断出的错误。您不应尝试运行存在此类问题的程序;而是解决问题。
这些是错误情况,因为您的代码不符合ISO C11。因此,未以任何方式定义程序的运行时行为。有些编译器通过将“警告”之类的条件描述为初学者并不容易。
显示的问题strdup
是调用的函数不在ISO C11中,但是您已经使用了该-std=c11
标志。如果“ dcc”编译器未提供此调用的诊断消息,则该编译器不合格。
可能的修复是:
-std=gnu11
char * strdup(const char *str1);
)strdup
; 改用malloc
后跟strcpy
。#define _XOPEN_SOURCE 700
,它将-std=c11
被该文件覆盖。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句