Rouftantical Rouftantical - 1 year ago 93
C Question

How does realloc() work?

Assuming that I have allocated memory using

, if I do in my code:

char *newline = realloc ( oldline , newsize );
// Assuming oldline is the pointer to which the starting address
// of the memory which malloc() has returned, is assigned and,
// say, newsize is integer having 100 value.

Now my questions regarding it are:-

  1. Is it necessary that
    will point to same address as
    , which holds the previous initial address?

  2. Is it so that in this case,
    will be freed(implicitly) and
    will take the charge of memory addressing?

  3. After the above code and after the work has been done, what should I do to free memory




    or both?

Answer Source

It depend if realloc was successful or not. If realloc is successful then:

  1. No ! For example, if there is not enough contiguous memory after oldline then newline will be different from oldline.

  2. Yes

  3. free(newline); since oldline has been freed if necessary. After a realloc oldline should be considered as invalid pointer.

If it is not successful. Then, you use oldline as if nothing happened, in particular you should free it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download