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?
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.