Search code examples
ccrashfree

Program crashing after using "Free()" command (C)


I have the following struct:

typedef struct employee
{
    int   name_length;
    char* name;
    float  salary;
} Employee;

and the following functions:

Employee** makeArr(char* fileName, int* size)
{
    FILE* f = fopen(fileName, "rb");
    checkOpenFile(f);
    Employee** arr = (Employee**)malloc(sizeof(Employee*));
    checkAllocation(&arr);
    int counter = 0;
    while (!feof(f))
    {
        
        int employeeNameSize;
        float employeeSalary;
        fread(&employeeNameSize, sizeof(int), 1, f);
        if (feof(f))
            break;
        char* employeeName = (char*)malloc(sizeof(char) * employeeNameSize+1);
        checkAllocation(&employeeName);
        fread(employeeName, sizeof(char), employeeNameSize, f);
        employeeName[employeeNameSize] = '\0';
        fread(&employeeSalary, sizeof(float), 1, f);
        arr[counter] = makeEmployee(employeeNameSize, employeeName, employeeSalary);
        counter++;
        realloc(arr, sizeof(Employee*)*(counter));
    }
    *size = counter;
    fclose(f);
    return arr;
} 

and:

void freeEmployeeArr(Employee** arr, int size)
{
    for(int i = 0; i < size; i++)
    {
        free(arr[i]->name);
        free(arr[i]);
    }
     free(arr); 
}

and this:

Employee* makeEmployee(int nameLength, char* name, float salary)
{
    Employee* tmp = (Employee*)malloc(sizeof(Employee));
    checkAllocation(&tmp);
    tmp->name_length = nameLength;
    tmp->name = name;
    tmp->salary = salary;
    return tmp;

}

my main:

void main(int argc, char* argv[])
{
    char* name1 = argv[1]; 
    char* name2 = argv[2];
    int size;
    Employee** ans = makeArr(name1, &size);
    freeEmployeeArr(ans, size);
}

The problem that I encounter:

free(arr);

crashes my program. If I remove this line, everything works fine. But this specific causes me some problems. If I'm trying to start without debugging, I get this message: enter image description here

and if I'm debugging, I get this message: enter image description here

I really have no idea what's wrong with my program. I've read that these kind of problems might appear when I realloc/malloc with a value of zero. But this is not the case.

Can anyone spot my mistake here? Thanks in advance.


Solution

  • The line

    realloc(arr, sizeof(Employee*)*(counter));
    

    is bad. You have to assign the new pointer returned to arr.

    It should be like this:

    Employee** newArr = realloc(arr, sizeof(Employee*)*(counter));
    if (newArr == NULL) {
        /* handle error, clean up and return from the function */
    }
    arr = newArr;