I wrote simple program, there is it:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *p = (int *)calloc(6, sizeof(int));
p[0] = 10;
p[1] = 20;
p[2] = 30;
p[3] = 40;
p[4] = 50;
p[5] = 60;
p[6] = 70;
p[7] = 80;
p[8] = 90;
p[9] = 100;
printf("hello world %d\n", p[9]);
free(p);
}
It not works and gives us error:
malloc(): corrupted top size
Aborted (core dumped)
This is logical because we added 6 ints to array. But now it's time for f*****g magic, i wrote this:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *p = (int *)calloc(7, sizeof(int));
p[0] = 10;
p[1] = 20;
p[2] = 30;
p[3] = 40;
p[4] = 50;
p[5] = 60;
p[6] = 70;
p[7] = 80;
p[8] = 90;
p[9] = 100;
printf("hello world %d\n", p[9]);
free(p);
}
And it works. We added 7 ints to array and it can contain 10 ints, how so? And the last question is why it:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *p = (int *)calloc(7, sizeof(int));
p[0] = 10;
p[1] = 20;
p[2] = 30;
p[3] = 40;
p[4] = 50;
free(p);
p[5] = 60;
p[6] = 70;
p[7] = 80;
p[8] = 90;
p[9] = 100;
printf("hello world %d\n", p[9]);
}
works?