Raman said:
Hi All,
Here is a small Code,
int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/
/** some stuff with p again**/
}
Others have said it, it's undefined behavior.
Here is a specific example. The numbers are specific to
one implementation I know of. Yours is most likely different.
On my example system, the heap is implemented by maintaining
the free memory blocks in a linked list.
Malloc goes through that list, trying to find a suitable block.
It may cut an existing one into fragments to avoid wasting
too much memory.
When a block is found, say at 0x12000, it gets unlinked from
the list and at the first location in the block the size is
stored. Malloc then returns a pointer to the first address
after that size (0x12004).
Free decrements the pointer by the correct amount (4 bytes),
retrieves the size and hooks the block back into the free list.
On such a system, your code isn't just a memory leak. In your
particular example, free would leak a small block of 10 bytes,
but also hook a free block starting at (p-4) into the free list,
with a size corresponding to the character sequence "3456".
This huge 'free' block is likely to overlap other free and used
memory. The next malloc could now hand out memory which is already
in use.
In other words, you are breaking the internal data structures
of the heap management, and after that anything may happen.
Kind regards,
Iwo