对于家庭作业,我正在尝试创建一个名为Student_List
的动态向量,但我对Add_Student
函数存在问题。
我收到以下错误:
Unhandled exception at 0x589BB2CE(msvcr120d.dll) in ConsoleApplication1.exe:
0xC00000005: Access violation reading location 0xCCCCCCCC8.
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int Assignment1;
int Assignment2;
int Assignment3;
int Assignment4;
int Assignment5;
int FinalGrade;
}Grade;
typedef struct{
int Id;
char *FirstName;
char *LastName;
Grade Grade;
}Student;
typedef struct{
Student *Students;
int Size;
}Student_List;
void Init_Student(Student *);
//CRUD
void Create_Student(Student **student);
void Read_Student(Student *);
void Update_Student(Student *);
void Delete_Student(Student **);
//Student Repository
void Add_Student(Student_List *List, Student*);
void Get_Student_By_Id(Student_List *List, int index);
void Remove_Student(Student_List *List, int index);
int main(){
//Create Student List
Student_List student_list;
student_list.Size = 0;
Student *student = NULL;
Create_Student(&student);
Read_Student(student);
Add_Student(&student_list, student);
Delete_Student(&student);
free(student_list.Students);
}
void Create_Student(Student **student){
*student = (Student*)malloc(sizeof(Student));
if (student == NULL){
printf("\nOut of memory!");
exit(1);
}
}
void Init_Student(Student *student){
student->FirstName = (char*)malloc(128 * sizeof(char));
student->LastName = (char*)malloc(128 * sizeof(char));
if (student->FirstName == NULL || student->LastName == NULL){
printf("\nOut of memory!");
exit(1);
}
}
void Read_Student(Student *student){
Init_Student(student);
printf("Introduzca el Nombre y el Apellido (ej: Max Medina): ");
scanf("%s %s", student->FirstName, student->LastName);
Grade grade;
printf("Introduzca las Calificaciones (ej: 7 8 9 10 6): ");
scanf("%d %d %d %d %d", &grade.Assignment1, &grade.Assignment2, &grade.Assignment3, &grade.Assignment4, &grade.Assignment5);
student->Grade = grade;
}
void Update_Student(Student *student){
Grade grade;
printf("Introduzca las Calificaciones (ej: 7 8 9 10 6): ");
scanf("%d %d %d %d %d", &grade.Assignment1, &grade.Assignment2, &grade.Assignment3, &grade.Assignment4, &grade.Assignment5);
student->Grade = grade;
}
void Delete_Student(Student **student){
free(*student);
}
void Add_Student(Student_List *List, Student *student){
//List->Size++;
List->Students = (Student*) realloc(List->Students, List->Size++ * sizeof(Student));
int index = List->Size - 1;
//List->Students[index] = *student;
}
答案 0 :(得分:1)
传递给realloc
的参数必须是指向先前使用malloc
,calloc
或realloc
分配的内存块的指针。
或者,此参数可以是空指针,在这种情况下会分配一个新块(就像调用malloc
一样)。
在你的代码中,它既不是。
您可以在将student_list.Students = NULL
传递给Add_Student
之前初始化{<1}}来解决此问题。