Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does realloc() work?

Tags:

c

realloc

Assuming that I have allocated memory using malloc(), 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 newline will point to same address as oldline, which holds the previous initial address?
  2. Is it so that in this case, oldline will be freed(implicitly) and newline 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

    free(newline);
    

    or

    free(oldline);
    

    or both?

like image 509
OldSchool Avatar asked Mar 29 '14 18:03

OldSchool


1 Answers

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.

like image 128
hivert Avatar answered Sep 20 '22 03:09

hivert