Search code examples
cmallocfree

Checking the memory requested two times


There is one thing which I'm not sure, hence the Question now, I hope that the title is OK here.

Lets check the following program first:

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

struct person{
    char *fn;
};

int main(void){
    struct person *pers;

    pers = malloc(sizeof(struct person));
    if(pers == NULL){
        printf("No memory Avaible\n");
        exit(1);
    }

    pers->fn = malloc(10000000000000000); /*requesting a big chunk*/
    if(pers->fn == NULL){
        printf("No memory Avaible =>> [pers->fn]\n");
        free(pers);
        exit(2);
    }


    strcpy(pers->fn, "Michi");
    pers->fn[strlen(pers->fn)] = '\0';

    printf("FN = %s\n",pers->fn);

    if(pers->fn){
        free(pers->fn);
    }

    if(pers){
        free(pers);
    }
}

The Output would be:

No memory Avaible =>> [pers->fn]

Because there is no memory available, I do a free on the pers and then exit:

if(pers->fn == NULL){
    printf("No memory Avaible =>> [pers->fn]\n");
    free(pers);
    exit(2);
}

Now lets say that we have enough memory and the program works fine, latter we come to this part:

if(pers->fn){
    free(pers->fn);
}

if(pers){
    free(pers);
}

Is there any guarantee that I should check if the memory is still there? Or I'm just fine with:

free(pers->fn);
free(pers);

Solution

  • No need to check at that point in the program. You could only get there if the the two previous malloc()s were a success.