Why Malloc store more Data then allocated Size

Piyush Panchariya
2 min readFeb 17, 2022

--

what is Malloc?

The simplest & most common way to implement memory allocation in C programming is to use the Malloc function which: allocates dynamic memory at runtime.

int *Var = (int*)malloc(100);

where,

“Var” is a pointer that store the memory address of the variable

“100” is the memory size we allocate in the heap memory

We allocate storage with malloc. This returns us the address(*Var) of where we may store our data. However, there is no one who will check if you store only in the area given to you. If you write beyond the area allocated, you are writing in an area that is “not yours”. This can lead to various types of undefined behavior.

Some memory managers will intercept your attempt and will abort your program. Other memory managers don’t do that, but since you write to an area that is not yours, you may be overwriting data from the memory manager, and any next attempt to allocate memory may fail because the memory manager’s data is corrupt. Or you are overwriting memory that belongs to someone else.

It may seem you can write more than you allocated, does not mean your program is correct. It is hopelessly wrong and will lead to an error somewhere else. So your program could make for example invalid calculations and your airplane crashes… This is called undefined behavior and you as a programmer must take care you always allocate what you need and that you never go out of the bounds of what you allocated.

--

--