【发布时间】:2018-02-27 20:52:50
【问题描述】:
我的代码有一个小问题,希望您能帮助我。 下面的程序读取写入 txt 文件的名称,并将它们存储在链表中,然后在命令行上打印出来。
该列表由以下名称组成:
Gustav Mahler
Frederic Chopin
Ludwig van Beethoven
Johann-Wolfgang Von-Goethe
但是当我运行程序时,程序的执行被中断,无论是在打印列表之前还是之后。
如果我删除最后一行,它会完美运行,但是当我将它添加回列表或用随机组合替换它时,例如“jlajfi3jrpiök+kvöaj3jiijm.--aerjj”,它会再次停止。
有人可以向我解释为什么程序执行会中断吗?
提前谢谢你! :)
这是程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct list {
char* name;
struct list *next;
}NODE;
char * getString(char *source);
int main() {
FILE *fpointer = NULL;
char filename[100];
puts("\nEnter the name of the file:\n");
gets(filename);
if((fpointer = fopen(filename, "r")) == NULL ) {
printf("\nThe file you have chosen is not valid.\n");
return 1;
}
char buffer[200];
NODE *head = NULL;
NODE *current = NULL;
while(fgets(buffer, 200, fpointer) != NULL) {
NODE *node = (NODE *) malloc(sizeof(NODE));
node -> next = NULL;
node -> name = getString(buffer);
if(head == NULL) {
head = node;
} else {
current -> next = node;
}
current = node;
}
current = head;
while(current) {
printf("%s", current -> name);
current = current -> next;
}
return 0;
}
char * getString(char* source) {
char* target = (char*) malloc(sizeof(char));
strcpy(target, source);
return target;
}
【问题讨论】:
-
malloc(sizeof(char))分配 1 字节,只够一个字符串终止符!建议char* target = malloc(strlen(source) + 1));甚至char* target = strdup(source);
标签: c debugging readfile singly-linked-list interruption