realloc

0

Witam,
Czy funkcja realloc po wywołaniu np * p=realloc(* p,sizeof(int)*(counter+1)),zmieni adres na nowy, i od razu zwolni pamięć na "stary"? czy należy przypisać do nowej zmiennej, zwolnić pamięć *p, i do *p przypisać nowy adres tej innej zmiennej?
Mam nadzieję że jest to zrozumiałe co mam na myśli

2

https://en.cppreference.com/w/c/memory/realloc
"On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with free() or realloc(). The original pointer ptr is invalidated and any access to it is undefined behavior (even if reallocation was in-place).

On failure, returns a null pointer. The original pointer ptr remains valid and may need to be deallocated with free() or realloc(). "

2

https://en.cppreference.com/w/c/memory/realloc
Ogólnie: jak się uda, to zwalnia starą pamięć; gorzej jeśli nie, bo nadpiszesz sobie wtedy stary wskaźnik a on nie zostanie zwolniony.

0

Dzięki wielkie

0

Specyfikacja POSIX mówi tyle:

"The realloc() function shall deallocate the old object pointed to by ptr and return a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes."

Jak widać, jest tam słówko "shall", a nie "must". Dlatego implementacja realloca może się różnie zachowywać na różnych systemach.

Big blue niejasno pisze:
"The use of realloc is discouraged because it can lead to memory leaks. It is preferred to use allocatable variables instead."

Osobiście unikam realloca jak mam coś w C naskrobać.
edycja:
Co prawda link IBMowy dla innego języka, ale realloc na AIX dziwnie mi się zachowywał w C.

1 użytkowników online, w tym zalogowanych: 0, gości: 1