Fresh storage (...) not released before assignment

From 433253

(Difference between revisions)
Line 1: Line 1:
Sample code:
Sample code:
-
<pre>
+
<code>
         int move;
         int move;
int *empty;
int *empty;
Line 9: Line 9:
move = empty[r];
move = empty[r];
         free(empty);
         free(empty);
-
</pre>
+
</code>
Error message:
Error message:
-
<pre>
+
<code>
game.c:115:2: Fresh storage empty (type int *) not released before assignment:
game.c:115:2: Fresh storage empty (type int *) not released before assignment:
                 empty = state_empty(s)
                 empty = state_empty(s)
Line 20: Line 20:
   warning)
   warning)
   game.c:114:2: Fresh storage empty created
   game.c:114:2: Fresh storage empty created
-
</pre>
+
</code>
Solution:
Solution:
-
????????????
+
The problem here is that the safe_malloc line is allocating a block of memory which empty is set to point to, but then on the next line empty is changed to point to the return of state_empty(), meaning there is now no longer anything pointing to the memory that safe_malloc returned, and thus it is lost (and leaked).  To fix this code, it is simply a matter of removing the safe_malloc() line, since the memory is not required.  In other situation you would need to put a free(empty) before you change the value of empty.

Revision as of 02:50, 24 August 2006

Sample code:

       int move;

int *empty; empty = safe_malloc(sizeof(int)*NUM_EMPTY); empty = state_empty(s); /* this is the bad line */ ... move = empty[r];

       free(empty);

Error message:

game.c:115:2: Fresh storage empty (type int *) not released before assignment:

                empty = state_empty(s)
 A memory leak has been detected. Storage allocated locally is not released
 before the last reference to it is lost. (Use -mustfreefresh to inhibit
 warning)
  game.c:114:2: Fresh storage empty created

Solution:

The problem here is that the safe_malloc line is allocating a block of memory which empty is set to point to, but then on the next line empty is changed to point to the return of state_empty(), meaning there is now no longer anything pointing to the memory that safe_malloc returned, and thus it is lost (and leaked). To fix this code, it is simply a matter of removing the safe_malloc() line, since the memory is not required. In other situation you would need to put a free(empty) before you change the value of empty.

Personal tools