0
#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.

王璘钰
  • 25
  • 2
  • 2
    You have demonstrated that undefined behavior of a C program does not necessarily manifest as the program crashing. Congratulations! This is an important thing to understand. – John Bollinger May 31 '21 at 03:08
  • you main that, this is an UB? – 王璘钰 May 31 '21 at 03:14
  • 2
    Of course it is. You allocate 25 ints and then access 30. UB means it may crash, it may produce wrong values, it may appear to "work" or any other unpredictable behaviour. – kaylum May 31 '21 at 03:44
  • Note that `malloc_usable_size()` is not a standard function in the sense that it is not part of Standard C or POSIX. It is likely routinely available on Linux; it is probably rarely available elsewhere. You will need to decide for yourself whether that matters. – Jonathan Leffler May 31 '21 at 03:46

0 Answers0