opensmalltalk-vm icon indicating copy to clipboard operation
opensmalltalk-vm copied to clipboard

code smell (IntelliSense C6308): realloc could cause a memory leak

Open nicolas-cellier-aka-nice opened this issue 6 years ago • 4 comments

In this pattern:

ptr = realloc( ptr , new_size );

realloc may fail when HEAP memory is exhausted, then return 0, and overwrite ptr with a NULL pointer... But realloc did not free(ptr), it rather leaves it untouched!

OK, we rarely exhaust HEAP nowadays, and consequences might be catastrophic anyway. But it is a code smell. It should be written like this:

aux = realloc( ptr , new_size ); if( aux == NULL ) /* handle_the_error */ {}; else ptr = aux;

See: https://github.com/OpenSmalltalk/opensmalltalk-vm/commit/82d1c33a1c5756b0a76bd37539d15a4824368d59#diff-ea77aa3cf89ad27f0980e8a8b857fb1cR585

krono avatar Jan 01 '19 22:01 krono

On 2019-01-01, at 1:39 PM, Nicolas Cellier [email protected] wrote:

In this pattern:

ptr = realloc( ptr , new_size );

realloc may fail when HEAP memory is exhausted, then return 0, and overwrite ptr with a NULL pointer... But realloc did not free(ptr), it rather leaves it untouched!

That's just... awful. If it can't realloc it should damn well leave the original alone

tim

tim Rowledge; [email protected]; http://www.rowledge.org/tim Useful random insult:- Not much to show for four billion years of evolution.

OpenSmalltalk-Bot avatar Jan 02 '19 01:01 OpenSmalltalk-Bot

Tim, to be sure about understanding: realloc does the right thing, it leaves the original alone. It's we, programmers that do not do the right thing: we overwrite a valid pointer with a NULL pointer. And now, there is no references to the valid pointer anymore => memory leak (+ eventually other side effects of having a NULL pointer hanging).

On 2019-01-02, at 7:12 AM, Nicolas Cellier [email protected] wrote:

Tim, to be sure about understanding: realloc does the right thing, it leaves the original alone. It's we, programmers that do not do the right thing: we overwrite a valid pointer with a NULL pointer.

Yeah, I thought I had cancelled my email once I realised that was what was going on. Apparently I overwrote the pointer with nil....

tim

tim Rowledge; [email protected]; http://www.rowledge.org/tim Strange OpCodes: ESBD: Erase System and Burn Documentation

OpenSmalltalk-Bot avatar Jan 02 '19 19:01 OpenSmalltalk-Bot