In my C program I am trying to allocate some memory with malloc() function, like this:
char *buf = (char *)malloc(size);
but the problem is that malloc() always returns non-NULL pointer. Even if I try to allocate enormous (size is 1E+13) amount of memory, it returns valid buf pointer. Of course after that program crashes.
But how can I detect that requested amount of memory is too large and will be not available, if returned buf value is not NULL?
Edit:
In comments I see that my question may be not clear. So this is more expanded sample:
unsigned long size = very_large_calculated_value;
char *buf = (char *)malloc(size);
if (buf == NULL) i_know_it_fails;
...
but Xcode runs this code and buf is never NULL whatever requested size is. So, very soon program crashes. How can I detect memory allocation failure if buf is not NULL, but obviously unuseable?
Edit:
To those who marked the question as a duplicate: There is no answer for the question "How can I detect memory allocation failure?", because the solution like "change some settings in your OS" is not an answer - I am asking for C code to detect memory allocation error, or something like "it is not possible to make programmatically".