#include <stdlib.h>
#include <malloc.h>
/*
* platform:
* linux3 centos6, gcc8.2
* x86-64 64bit ELF
*/
int main()
{
int* p = (int*)malloc(sizeof(int) * 25);
size_t sz = malloc_usable_size(p);
printf("%u\n", sz / sizeof(int)); // which is 26
for (int i = 0; i < 30; i++) {
p[i] = 1;
}
}
This code won't crash. Amazing!I use malloc to request a heap memory to store 25 ints. However, when i touch memory which is beyond the 25, it won't crash. why? malloc may return a larger heap memory than paramters, so i call malloc_usable_size, however, the return of this function is 26, still smaller than 30.