Bug 14981 - mtrace realloc
Summary: mtrace realloc
Status: RESOLVED FIXED
Alias: None
Product: glibc
Classification: Unclassified
Component: malloc (show other bugs)
Version: unspecified
: P2 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2012-12-22 15:02 UTC by Joost VandeVondele
Modified: 2014-06-14 05:30 UTC (History)
2 users (show)

See Also:
Host:
Target:
Build:
Last reconfirmed:
fweimer: security-


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Joost VandeVondele 2012-12-22 15:02:08 UTC
The following program causes mtrace.pl to report memory leaks.

> cat test.c
void main()
{ 
  int* i;
  mtrace();
  i=malloc(sizeof(int));
  i=realloc(i,0);
  muntrace();
} 

mtrace ./t.dat 

Memory not freed:
-----------------
           Address     Size     Caller
0x0000000000a96460      0x4  at 0x400678

It looks like mtrace.pl is not considering realloc(x,0) equivalent to a free.
Comment 1 Rich Felker 2012-12-23 02:31:08 UTC
This program has a memory leak. On glibc, malloc(0) and realloc(i, 0) both return a unique pointer that cannot be dereferenced. Failure to free this pointer is a memory leak.

realloc(i, 0) is only equivalent to free(i) on implementations where malloc(0) returns 0.

I suspect you're confused by the language in POSIX that says "If size is 0 and ptr is not a null pointer, the object pointed to is freed." This does not preclude a memory leak. Note that POSIX later says "If size is 0, either a null pointer or a unique pointer that can be successfully passed to free() shall be returned." The confusion stems from the fact that POSIX has misleadingly reworded the specification of free to refer to "changing the size of an object", a concept which ISO C intentionally avoids. In the ISO C language, a successful realloc _always_ frees the original object, and returns a pointer to a new object with the same contents (up to the minimum of the old and new size).
Comment 2 Andreas Schwab 2012-12-23 08:36:20 UTC
In glibc realloc(0,s) == malloc(s), and realloc(i,0) == (free(i),0) for i != 0.
Comment 3 jsm-csl@polyomino.org.uk 2012-12-23 16:31:05 UTC
Regarding realloc with size 0, see also 
<http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_400.htm>.  Some of the 
problems with its semantics arose out of a change in C99 to the wording 
that was used in C90.
Comment 4 Andreas Schwab 2013-01-03 10:20:41 UTC
Fixed in 2.18.
Comment 5 Jackie Rosen 2014-02-16 17:50:44 UTC Comment hidden (spam)