Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understanding malloc: Why doesn't my program crash, when I exceed allocated memory?

I have tinkered around with malloc to understand better how is works.
I wrote this program:

int *array = (int *)malloc(100 * sizeof(int));

for (int i = 0; i < 5000; i++) {
    array[i] = 10;
}
// Element with index 4999 has a correct value 
printf("%d\n", array[4999]);

return 0;

Actually I would expect the program to crash, because I have allocated memory for only 100 integer. But I write 5000 integers into the pointer-array. The element 5000 in the array has even the correct value.

What happens here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does it automatically allocate more memory, when needed? But in this case: What sense does the initial allocation have, which is given as an argument?

>Solution :

You are using memory which does not belong to you. Various things could happen, including a crash but also you might read a different value than you write, or you might cause your fax-modem to dial the White House when you write.

It’s like building a house on land you don’t own. Maybe you can live there undisturbed for years. Maybe the government will tear it down. Maybe the land is a disused uranium mine.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading