1
char *str = malloc(1000); // that is ok
// do somthing ...
free(str);

//but what if i didn't protect malloc from failure 

// i mean doing that
char *str = malloc(1000);
if (!str)
    return (0);
//do something ...
free (str); 

so how can malloc fail on reserving memory in heap and what is the error that can happened

  • 3
    If you don't check the returned pointer and use it when it is NULL you have undefined behavior. Odds are high your program will crash. – Retired Ninja Jun 11 '22 at 03:09
  • @RetiredNinja first thank u for your answer, yah i know that but when does malloc fail and return NULL and not a pointer and how can it return NULL that's what i want know actually. – Mittous Issmail Jun 11 '22 at 03:17
  • 2
    It will return `NULL` if it can't provide the amount of memory you requested. [Example](https://godbolt.org/z/6K35Y7czo) – Ted Lyngmo Jun 11 '22 at 03:20
  • but is it possible to run out of memory @TedLyngmo and how can that happened and thank u for you answer – Mittous Issmail Jun 11 '22 at 03:22
  • 3
    @MittousIssmail It is possible to run out of memory _handles_, out of memory, or [lie to you](https://stackoverflow.com/a/19991656/2410359) and fail later. – chux - Reinstate Monica Jun 11 '22 at 03:23

0 Answers0