openrave icon indicating copy to clipboard operation
openrave copied to clipboard

Fix realloc memory leak

Open lazydroid opened this issue 1 year ago • 3 comments

realloc() may return NULL, so when we do:

foobar = realloc( foobar );

we risk leaking memory, better implementation would be:

maybe_good = realloc( foobar )
foobar = maybe_good != NULL ? maybe_good : foobar
....
free( foobar )

lazydroid avatar Oct 28 '24 09:10 lazydroid

the change did not seem to break anything important

image

lazydroid avatar Oct 28 '24 11:10 lazydroid

log however many bytes were written to the buffer before it failed

I'm not sure there's anything guaranteed to be written if there's not enough space: "A negative number is returned on failure, including when the resulting string to be written to ws would be longer than n characters."

lazydroid avatar Oct 29 '24 06:10 lazydroid

Nothing is guaranteed, but the implementation in glibc writes directly to the buffer as it goes, so you will likely have some large fraction of wslen bytes holding valid formatted data (assuming this is not the first call to realloc, in which case the valid data is in the stacked buffer, but same idea). Sticking a \0 on the end of the buffer in the failure case and returning wslen bytes written would attempt to print as much as it could, with some amount of junk on the end.

This is mostly an idle thought - I think we are unlikely to hit this codepath regardless.

rschlaikjer avatar Oct 29 '24 08:10 rschlaikjer