c - Is it possible to free a char * allocated with a calloc" -


i know if it's possible free char * (string) allocated calloc several times.

char * signal;    (int = 0 ; < n ; i++)  {       signal = (char*) calloc(n, sizeof(char));    if (a = true) {       signal[i] = 1;    }     /* stuff */     free(signal); /* error here : double free or corruption */    } 

why error on free()?

would know if it's possible free char * (string) allocated calloc several times.

short answer: no

long answer: 1 call malloc(), calloc(), realloc(null, ...)(*1) allows (requires, not leak memory) exactly one call free() passing value latter returned 1 of former.

so, if passing free()ed address free() , assuming had not been returned allocation after previous call free(), code invokes undefined behaviour, can happen on.


(*1) notes on realloc():

  • successive calls realloc() not passing null not increment sum of necessary calls free(). in other words

    char * p = malloc(42); p = realloc(43); 

    does require one call free()

    free(p); 
  • passing null realloc() makes realloc() count call malloc().

    doing

    char * p = realloc(null, 42);  

    is same doing

    char * p = malloc(42); 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -