Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic memory allocation of integer array

Tags:

c

malloc

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

like image 783
user2081740 Avatar asked Jul 09 '13 02:07

user2081740


2 Answers

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


* Arguably, the worst.
like image 139
Oliver Charlesworth Avatar answered Sep 28 '22 02:09

Oliver Charlesworth


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.

like image 44
Travis DePrato Avatar answered Sep 28 '22 01:09

Travis DePrato