I learned about Dynamic Memory Allocation in C today. I learned how memory can be allocated to a char array with the malloc()
from stdlib.h
when I need to print a sentence. But then I saw I was able to store more bytes then I assigned. Here is my entire code.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i;
char *foo;
foo = (char*)malloc(20);
for (i=0;i<30;i++)
{
foo[i]='a';
printf("\n%d) %c",i+1,foo[i]);
}
return 0;
}
Output
1) a
2) a
3) a
4) a
5) a
6) a
7) a
8) a
9) a
10) a
11) a
12) a
13) a
14) a
15) a
16) a
17) a
18) a
19) a
20) a
21) a
22) a
23) a
24) a
25) a
26) a
27) a
28) a
29) a
30) a
As you can see I gave foo
20 bytes but was able to store 30 bytes in it. What is going on? Did I misunderstand malloc()
?