Code snippet, at the bottom, which I was trying lead to the following error
free(): invalid next size (fast)
Above error, was caused by declaration of integer variable mock after accidently calling memset() on pointer check with size more than what was originally allocated using malloc(). And when free() is called on pointer check it leads to a runtime error.
It would be helpful if somebody could explain how the internal memory is being manipulated or why this error actually occurred.
Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *check = (char *)malloc(sizeof(char) * 10);
memset(check, 0, 100);
memcpy(check, "memsetcpy", 10);
int mock = 9;
free(check);
return 1;
}
EDIT My intention of asking the question was to know/understand what happens to the book-keeping information in the heap memory when the program runs. And may be to have some information on data structures that are modified would be great. OR I wanted to know from the design perspective.
Thanks everyone for chipping-in.
A typical dynamic memory (heap) implementation stores a lot of household information right there, in the very same memory, interleaved with user data. Each block of memory you allocate typically includes a special header region and, possibly, a special footer region. These regions surround your user region from both ends. You are only allowed to manipulate memory inside your user region. But the moment you write anything outside the boundaries of that user region, you most certainly damage those internal header and footer regions. This completely destroys the integrity of dynamic memory management subsystem. The rest follows.
In your case you go outside your user region by 90 bytes. This is a lot. You probably destroyed a lot of internal household data that is critical for proper operation of dynamic memory.
The specific details of this (what gets damaged and how it affects free
later) are very, very, very implementation-dependent. Different implementations can be wildly different in that regard. There's no way to provide a more specific description without at least knowing what specific implementation you are using.