重新分配包含指向另一个Sruct指针的Struct(分段错误)

时间:2017-04-02 08:14:49

标签: c pointers struct realloc

我有两个这样的结构:

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");
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

问题解决了!

感谢@StoryTeller建议使用valgrind来调试内存错误。记忆被程序中的其他东西弄乱了。

相关问题