重新分配一个包含指向另一个结构的指针的结构(分段错误)
Realloc a Struct which contains a pointer to another Sruct (Segmentation Fault)
我有两个这样的结构:
typedef struct Student {
char name[80];
char sclass[4];
int phone;
} Student;
typedef struct Cell {
Student* p_student; // pointer to struct
bool occupied; // if the cell has been occupied for collisions after delete
} Cell;
以及最初使用 malloc 分配的两个数组:
Cell *arr_name = malloc(sizeof(Cell) * size),
*arr_phone = malloc(sizeof(Cell) * size);
问题是,当我尝试使用 Realloc 时出现分段错误:
void insert(int *size, int *numberOfStudents, Cell **arr_name, Cell **arr_phone, char name[80], char sclass[4], int phone) {
// some stuff happening
if(*numberOfStudents > (*size / 1.5)) {
*size = *numberOfStudents * 1.5;
int new_size = sizeof(Cell) * (*size);
Cell *p_name = realloc(*arr_name, new_size); // <-- ERROR HERE
Cell *p_phone = realloc(*arr_phone, new_size);
if(p_name && p_phone) {
*arr_name = p_name;
*arr_phone = p_phone;
}
else printf("Couldn't allocate more memory");
}
感谢您的帮助!
问题已解决!
感谢@StoryTeller 建议使用 valgrind 调试内存错误。内存被程序中的一些其他东西弄乱了。
我有两个这样的结构:
typedef struct Student {
char name[80];
char sclass[4];
int phone;
} Student;
typedef struct Cell {
Student* p_student; // pointer to struct
bool occupied; // if the cell has been occupied for collisions after delete
} Cell;
以及最初使用 malloc 分配的两个数组:
Cell *arr_name = malloc(sizeof(Cell) * size),
*arr_phone = malloc(sizeof(Cell) * size);
问题是,当我尝试使用 Realloc 时出现分段错误:
void insert(int *size, int *numberOfStudents, Cell **arr_name, Cell **arr_phone, char name[80], char sclass[4], int phone) {
// some stuff happening
if(*numberOfStudents > (*size / 1.5)) {
*size = *numberOfStudents * 1.5;
int new_size = sizeof(Cell) * (*size);
Cell *p_name = realloc(*arr_name, new_size); // <-- ERROR HERE
Cell *p_phone = realloc(*arr_phone, new_size);
if(p_name && p_phone) {
*arr_name = p_name;
*arr_phone = p_phone;
}
else printf("Couldn't allocate more memory");
}
感谢您的帮助!
问题已解决!
感谢@StoryTeller 建议使用 valgrind 调试内存错误。内存被程序中的一些其他东西弄乱了。