felikowski
felikowski

Reputation: 21

Why does realloc() crash my program?

I am trying to resize an array dynamically through the use of realloc. This array is initialized outside of my function using malloc.

Here's my function:

size_t verarbeite_anlagendatei(ANLAGE *anlage_arr) {    
    FILE *fp;
    ANLAGE anlage;

    fp = fopen("anlagen.dat", "r");

    if(fp == NULL) {
        printf("Anlagedatei existiert nicht. Bitte mit Menuepunkt (0) weiter machen.\n");
        return 0;
    }

    int index = 0;
    size_t size = 1;

    while(fscanf(fp, "%d %s %s %f %d %d",   
                &anlage.InventarNr, 
                anlage.Anlagenbez, 
                anlage.Standort, 
                &anlage.Basiswert, 
                &anlage.Nutzdauer, 
                &anlage.AnschJahr) != EOF) {
        if(index > 0) {
            size++;
            realloc(anlage_arr, size * sizeof(ANLAGE));
        }
        anlage_arr[index] = anlage;
        index++;
    }
    return size;    
}

I know that I have to initialize a new pointer to the ANLAGE type and check if it's NULL after my call to realloc, but since this function always crashes the program, I've skipped it in this case.

Upvotes: 0

Views: 3757

Answers (1)

In addition to the many fine points made in comments above, you need to be aware that realloc returns a pointer to the memory block it has allocated which may not be in the same location as the pointer it was passed. In other words, after calling realloc the original memory pointed to by your pointer (in this case, anlage_arr) may have been released, and the pointer returned by realloc must be used to access the re-allocated memory.

I suggest that you might want to rewrite your function as follows:

size_t verarbeite_anlagendatei(ANLAGE **p_anlage_arr) {    
    FILE *fp;
    ANLAGE anlage;

    fp = fopen("anlagen.dat", "r");

    if(fp == NULL) {
        printf("Anlagedatei existiert nicht. Bitte mit Menuepunkt (0) weiter machen.\n");
        return 0;
    }

    int index = 0;
    size_t size = 1;

    while(fscanf(fp, "%d %s %s %f %d %d",   
                &anlage.InventarNr, 
                anlage.Anlagenbez, 
                anlage.Standort, 
                &anlage.Basiswert, 
                &anlage.Nutzdauer, 
                &anlage.AnschJahr) != EOF) {
        if(index > 0) {
            size++;
            *p_anlage_arr = realloc(*p_anlage_arr, size * sizeof(ANLAGE));
        }
        (*p_anlage_arr)[index] = anlage;
        index++;
    }
    return size;    
}

A call to this function would look something like

ANLAGE *anlage_arr;
size_t sz;

anlage_arr = malloc(sizeof(ANLAGE));

sz = verarbeite_anlagendatei(&anlage_arr);

Best of luck.

Upvotes: 2

Related Questions