Paul Lemarchand
Paul Lemarchand

Reputation: 2096

Realloc a Struct which contains a pointer to another Sruct (Segmentation Fault)

I have two Structs like this:

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;

And two arrays that are initially allocated with malloc :

Cell *arr_name = malloc(sizeof(Cell) * size),
     *arr_phone = malloc(sizeof(Cell) * size);

The problem is, when I try to use Realloc I get the segmentation fault error :

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

Thanks for help !

Upvotes: 0

Views: 141

Answers (1)

Paul Lemarchand
Paul Lemarchand

Reputation: 2096

Problem solved !

Thanks to @StoryTeller that suggested to use valgrind to debug memory errors. The memory was messed up by some other stuff in the program.

Upvotes: 1

Related Questions