Why Malloc store more Data then allocated Size

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.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Image Stream Processing in Flutter application by TFLite Neural Networks

Tech & Startup Review Mid 2020

Deconstructing Kubernetes with Bryan Liles

How to Customize Your Terminal and BASH Profile from Scratch

what is an Array in java?

The Common Big Mistake in WebService Design

Unity Development — Animated Tiles

TCP/IP to Web 3.0: The Digital Story of a New Internet on Flux

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Piyush Panchariya

Piyush Panchariya

More from Medium

The Future of Technology in War Time

Trachtenberg system of multiplication by 11 and 12

Explaining Lionel Messi’s struggles with data: dribbles per 90'

The NIH RFI on genomic data sharing — Protecting genomic data