I am trying to create an array of size 2, dynamically, using malloc. Here is my code:
int *d = (int*)malloc(2 * sizeof(int));
d[0] = 4;
d[1] = 5;
d[2] = 8;
d[3] = 9;
d[4] = 7;
int i;
for (i = 0; i < 5; i++)
printf("%d \n", d[i]);
When I run this code, it prints 4, 5, 8, 9, 7
.
I am wondering how it was able to allocate more memory (5 integers) than I requested (2 integers)?
i wondering how it was able to allocate more memory than I requested.
It didn't. You are invoking undefined behaviour. One possible outcome* is that your program appears to "work".
Like Oli said, it's undefined. It may work, it may not. But the reality is that even though it might work 99% of the time, it will, at least once, fail, and you'll get a SEGFAULT
from reading or writing memory that your process isn't supposed to be using, and you'll also end up with virtually un-debugable memory leaks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With