0

I've been writing a small program that will allow the user to read a file, create a small "database" and the ability to create / delete entries, etc. When I try to use the

realloc()

function, it crashes.

Not sure if I am doing something wrong, probably am though, since I'm rather new to C.

So, I try to do it this way:

StudentDB database;
//More code in between, that does include malloc()
database->students = realloc(database->students, (database->numberOfStudents + 1) * sizeof(Student));
//It crashes when it gets to that part. 

What I am trying to do is use the realloc() function for a pointer that's inside a struct.

This is the entire program so far:

#include <stdio.h>
#include <stdlib.h>

typedef struct Lesson {
    char *name;
    int semester;
    float grade;
} Lesson;

typedef struct Student {
    char *name;
    char *surname;
    int id;
    int numberOfLessons;
    Lesson *lesson;
} Student;

typedef struct Database {
    int numberOfStudents;
    Student *student;
} StudentDB;

static int maxNameSize = 100;
static int autoclear = 1;


void addStudent(FILE *studentFile, StudentDB *database) {
    database->numberOfStudents++;
    printf("\nAdded +1 to number of students");
    database->student = realloc(&database->student, 10);
//  
//  printf("Name of the student: ");
//  scanf("%s", database.student[database.numberOfStudents].name);
}

void clear() {
    if(autoclear) {
        system("cls");
    }
}

Lesson getNextLesson(FILE *studentFile) {
    Lesson lesson;

    lesson.name = malloc(maxNameSize * sizeof(char));
    if(!lesson.name) { printf("Memory Allocation has failed. Exiting the program!"); exit(0); }
    fscanf(studentFile, "%s", lesson.name);

    fscanf(studentFile, "%d", &lesson.semester);

    fscanf(studentFile, "%f", &lesson.grade);

    printf("\n\t%s %d || %.2f\n", lesson.name, lesson.semester, lesson.grade);
    return lesson;
}

Student getNextStudent(FILE *studentFile) {
    Student student;

    student.name = malloc(maxNameSize * sizeof(char));
    if(!student.name) { printf("Memory Allocation has failed. Exiting the program!"); exit(0); }
    fscanf(studentFile, "%s", student.name);

    student.surname = malloc(maxNameSize * sizeof(char));
    if(!student.surname) { printf("Memory Allocation has failed. Exiting the program!"); exit(0); }
    fscanf(studentFile, "%s", student.surname);

    fscanf(studentFile, "%d", &student.id);

    fscanf(studentFile, "%d", &student.numberOfLessons);

    printf("%d || %s %s || %d\n", student.id, student.name, student.surname, student.numberOfLessons);

    int lesson;

    student.lesson = malloc(student.numberOfLessons * sizeof(Lesson));

    for(lesson = 0; lesson < student.numberOfLessons; lesson++) {
        student.lesson[lesson] = getNextLesson(studentFile);
    }
    return student;
}

void loadStudents() {

}

void run(FILE *studentFile, StudentDB *database) {
    int answer;
    do {
        clear();
        answer = menu();
        switch(answer) {
            case 1: {

                break;
            }
            case 2: {

                break;
            }
            case 3: {
                addStudent(studentFile, &database);
                break;
            }
            case 4: {

                break;
            }
        }
    } while(answer < 0 || answer > 9);
}

int menu() {
    int answer;
    printf("1. Load students records from file\n");
    printf("2. Save students records to file\n");
    printf("3. Add a student record\n");
    printf("4. Delete a student record by student id\n");
    printf("5. Display a student record by student id\n");
    printf("6. Display a student record by student surname\n");
    printf("7. Display all student records\n");
    printf("8. Find the lesson average for all students\n");
    printf("9. Exit\n");

    printf("Enter the number of the thing you would like to do: ");
//  scanf("%d", &answer);
    return 3;
}

void programInfo() {
    printf("\n\n====================================================\n\tProgram Info\n\n This program was created by KKosyfarinis\n\n [email protected]\n====================================================\n\n");
}

void readData(FILE *studentFile, StudentDB *db) {
    int i;

    printf("Running the loop\n");
    for(i = 0; i < db->numberOfStudents; i++) {
        printf("=====================\n\n\tStudent #%d\n", i);
        db->student[i] = getNextStudent(studentFile);
        printf("\n\tCompleted\n\n=====================\n");
    }

    clear();
}

void saveStudents() {

}

void main() {

    system("color 02");
    system("@echo off");

    FILE *studentFile;
    StudentDB database;

    studentFile = fopen("students.txt", "r+w");

    int numberOfStudents;

    //Set the number of students
    fscanf(studentFile, "%d", &database.numberOfStudents);

    //Prints the number of students
    printf("Number of students: %d\n", database.numberOfStudents);

    //Set the memory allocation
    database.student = malloc(database.numberOfStudents * sizeof(Student));
    if(!database.student) {
        printf("The memory allocation has failed. Exiting the program!");
        exit(0);
    }   

    //Read the students
    readData(studentFile, &database);   

    programInfo();
    run(studentFile, &database);

}

Thanks in advance for any help!

0

2 Answers 2

4

You're two code blocks have differing lines. One of which (the larger one) is incorrect. You are passing in a dereference to the student pointer? That's not needed, just pass the pointer itself.

database->student = realloc(&database->student, 10);

Should be:

database->student = realloc(database->student, 10);

You are also not passing in a realistic size, but your first code sample was. Does the following line not work?

database->students = realloc(database->students, (database->numberOfStudents + 1) * sizeof(Student));

That was just copied from your question. I'm confused as to what you have/have not tried and which one gives you the error.

Also, in the future provide more of a minimal example that still produces the error. There's also a chance you would figure out the issue while stripping the code down.

Sign up to request clarification or add additional context in comments.

2 Comments

Basically what I am trying to use realloc() for a pointer that is inside a struct
Well the -> operator already dereferences the struct StudentDB* Database.
2

What with this line ?

 addStudent(studentFile, &database);

in run function ? Where pointer to local variable is taken and passed to addStudent function

void run(FILE *studentFile, StudentDB *database) {
   ...
   case 3: {
      addStudent(studentFile, &database);  // <-- get pointer to local variable

i think this code cannot work even with Nick's changes without this modification

addStudent(studentFile, database);

1 Comment

Thank you! You are right, A pointer to a pointer. Thanks for that, still rather new to C. Will watch out for those in the future!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.