I'm coming from Python. So, I'm trying to understand malloc in C
This code works fine as expected:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
arr = (int *)malloc(2 * sizeof(int));
arr[0] = 123123123;
arr[1] = 456456456;
printf("%d\n", arr[1]);
return 0;
}
I suppose I should not be able to create arr[3]. I even able to create arr[5], this works fine as well:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
arr = (int *)malloc(2 * sizeof(int));
arr[0] = 111111111;
arr[1] = 222222222;
arr[2] = 333333333;
arr[3] = 444444444;
arr[4] = 555555555;
arr[5] = 666666666;
printf("%d\n", arr[1]);
printf("%d\n", arr[5]);
return 0;
}
Result:
x@main:~$ gcc example.c
x@main:~$ ./a.out
222222222
666666666
Why does it work? I created arr with 2 * sizeof ...
When I create arr[6], it crashes:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
arr = (int *)malloc(2 * sizeof(int));
arr[0] = 111111111;
arr[1] = 222222222;
arr[2] = 333333333;
arr[3] = 444444444;
arr[4] = 555555555;
arr[5] = 666666666;
arr[6] = 777777777;
printf("%d\n", arr[1]);
printf("%d\n", arr[5]);
return 0;
}
Result:
x@main:~$ gcc example.c
x@main:~$ ./a.out
malloc(): corrupted top size
Aborted (core dumped)
Why doesn't it work? arr[5] works. But arr[6] doesn't work.
I increase memory space from 2 to 3 and it still doesn't work:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
arr = (int *)malloc(3 * sizeof(int));
arr[0] = 111111111;
arr[1] = 222222222;
arr[2] = 333333333;
arr[3] = 444444444;
arr[4] = 555555555;
arr[5] = 666666666;
arr[6] = 777777777;
printf("%d\n", arr[1]);
printf("%d\n", arr[5]);
return 0;
}
Result:
x@main:~$ gcc example.c
x@main:~$ ./a.out
malloc(): corrupted top size
Aborted (core dumped)