我正在学习链表以及如何使用链表,并且我制作了一个简单的程序,使用这种方法来存储和打印学生的年龄和姓名。我想做其他事情,我想将学生的数据存储在一个文本文件中。但是,当我尝试写入此文件时,它会引发semengation错误错误。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
typedef struct student {
char * name;
int age;
struct student *next;
}student;
student * createStudent(char *, int);
student * append(student *, student *);
void printStudents(student *, int);
void storeStudents(student *, int, int flag);
int main(){
student *end, *start , *newStudent, *tmp;
int studentAge, nStudents, i = 1;
char * studentName = (char *)malloc(sizeof(char) *50);
if(!studentName){
printf("Couldn't allocate the memory\n");
exit(EXIT_FAILURE);
}
printf("Enter the number of students : ");
scanf("%d", &nStudents);
while(nStudents > 0){
printf("Enter the age from the %d student: ", i);
scanf("%d", &studentAge);
printf("Enter the name from the %d student: ", i);
scanf("%s", studentName);
if((i-1) ==0){
start = createStudent(studentName, studentAge);
end = start;
storeStudents(start, i , 0);
printStudents(start, i);
}else{
newStudent = createStudent(studentName, studentAge);
end = append(end, newStudent);
storeStudents(end, i , 1);
printStudents(end, i);
}
nStudents--;
i++;
}
tmp = start -> next;
free(start);
start = tmp;
tmp = start->next;
free(start);
free(tmp);
return 0;
}
void printStudents(student * start, int i){
if(start != NULL) printf("Student number %d\nName: %s\nAge: %d\n", i, start -> name, start -> age);
return;
}
void storeStudents(student * ptr, int i, int flag){
FILE *pfile = NULL;
switch (flag){
case 0: pfile = fopen("students.txt", "w+"); break;
case 1: pfile = fopen("students.txt", "a+"); break;
}
if(!pfile){
fprintf(stderr, "Couldn't open the file\n");
exit(EXIT_FAILURE);
}
else if(ptr != NULL){
fprintf(pfile, "Student number %d\nName: %s\nAge: %s\n", i, ptr -> name, ptr -> age);
}
fclose(pfile);
pfile = NULL;
return;
}
student * createStudent(char * name, int age){
student * ptr = NULL;
ptr = (student *) malloc(sizeof(student));
ptr->name = (char *)malloc(sizeof(char) *50);
if(!ptr || !(ptr ->name)){
printf("Couldn't allocate the memory\n");
exit(EXIT_FAILURE);
}
ptr-> age = age;
ptr ->name = name;
ptr ->next = NULL;
return ptr;
}
student * append(student * end, student * new){
end->next = new;
end = new;
return end;
}
该错误发生在函数storeStudents中。
什么原因导致此错误?
答案 0 :(得分:2)
好吧,我用一个在线C编译器/调试器运行了这段代码,它告诉我segfault位于fprintf()行上,在该行上您在age输出中不匹配类型字符串/ int类型。
这与您的createStudent不执行字符串复制并且不释放所有malloc的内存结合在一起,都是造成应用程序错误的原因。
我通过以下方式重新运行您的代码:
fprintf(pfile, "Student number %d\nName: %s\nAge: %d\n", i, ptr -> name, ptr -> age);
它不再存在段错误。
请同时解决其他问题。