Insure++ Reference - LEAK_FREE
This problem can occur when a block of memory contains a pointer to
another dynamically allocated block, as indicated in the following
figure.
If the main memory block is freed its memory becomes invalid, which
means that the included pointer can no longer be used to free the second
block. This causes a permanent memory leak.
This code defines PB to be a data structure that
contains a pointer to another block of memory.
1: /*
2: * File: leakfree.c
3: */
4: #include <stdlib.h>
5:
6: typedef struct ptrblock {
7: char *ptr;
8: } PB;
9:
10: main()
11: {
12: PB *p;
13:
14: p = (PB *)malloc(sizeof(*p));
15: p->ptr = malloc(10);
16:
17: free(p);
18: return (0);
19: }
We first create a single PB and then allocate a
block of memory for it to point to. The call to free on the
PB then causes a permanent memory leak, since it
frees the memory containing the only pointer to the second allocated
block. This latter block can no longer be freed.
[leakfree.c:17] **LEAK_FREE**
1. >> free(p);
2. Memory leaked freeing block: <return>
3. Lost block: 0x00013888 thru 0x00013891 (10 bytes)
block allocated at:
malloc() (interface)
main() leakfree.c, 15
Stack trace where the error occurred:
4. main() leakfree.c, 17
- Source line at which the problem was detected.
- Description of the problem and the value that is about to be lost.
- Description of the block of memory that is about to be lost,
including its size and the line number at which it was allocated.
- Stack trace showing the function call sequence leading to the
error.
In many cases, this problem is caused by forgetting to free the
enclosed blocks when freeing their container. This can be corrected by
adding a suitable call to free the memory before freeing the parent
block.
Caution must be used when doing this, however, to ensure that the
memory blocks are freed in the correct order. Changing the example in
the following manner, for example, would still generate the same error:
free(p);
free(p->ptr);
because the blocks are freed in the wrong order. The contained blocks must
be freed before their parents, because the memory becomes invalid as soon as
it is freed. Thus, the second call to free in the above code
fragment might fail, because the value p->ptr is no
longer valid. It is quite legal, for example, for the first call to
free to have set to zero or otherwise destroyed the contents of
its memory block.(1)
Some applications may be unable to free memory blocks and may not need
to worry about their permanent loss. To suppress these error messages in
this case add the line
insure++.suppress LEAK_FREE
to the .psrc file.
Footnotes- (1)
- Many systems
allow the out of order behavior, although it is becoming less portable as
more and more systems move to dynamically re-allocated (moveable) memory
blocks.
LEAK_ASSIGN
LEAK_RETURN
|