Search code examples
cmemoryrealloc

Initializing the memory using realloc()


The question about realloc().

If I want to size up the memory I allocated before with realloc().

Will the additional memory be initialized to 0 just like calloc() or not?

The second question is:

    int * p =(int*)malloc(10*sizeof(int));
    int* s = (int*)realloc(p,20);
    p=s;

Is assigning s to p a good way to resize the pointer p?

And can we realloc() the memory allocated with calloc()?


Solution

  • Will the additional memory be initialized to 0?

    No.

    can we realloc() the memory allocated with calloc()?

    Yes.

    Is assigning s to p a good way to resize the pointer p

    Depends.

    Just doing

    int * p = malloc(...);
    int * s = realloc(p, ...);
    p = s;
    

    is the same as

    int * p = malloc(...);
    p = realloc(p, ...);
    int * s = p;
    

    In both cases, if realloc() fails (and with this returned NULL) the address of the original memory is lost.

    But doing

    int * p = malloc(...);
    
    {
      int * s = realloc(p, ...); /* Could use a void* here as well. */
      if (NULL == s)
      {
         /* handle error */
      }
      else
      {
        p = s;
      }
    }
    

    is robust against failures of realloc(). Even in case of failure the original memory is still accessible via p.

    Please note that if realloc() succeeded the value of the pointer passed in not necessarily addresses any valid memory any more. Do not read it, nor read the pointer value itself, as doing this in both cases could invoke undefined behaviour.