Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

1) No.. in fact newline is not used at all (other than to store the results), why would you ask that?

2) Yes

3) Only the first.

C standard for realloc(old, size):

  • size == 0
    • realloc might free old and return 0
    • alternatively realloc behaves as for size != 0 but cannot return 0
  • size != 0
    • realloc might return 0. old is not touched
    • if the block pointed to by old is >= size, realloc might return old
    • alternatively realloc allocates a block >= size, copies all bytes from old up to size, frees old and returns this new block

You are responsible for whichever block persisted through this algorithm / was allocated. Working those out:

1 No. Though it can be.

2 Yes, If size == 0 or returned != 0

3a free oldline, if returned 0 and size != 0

3b free newline, if returned != 0

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top