How detect malloc failure?

后端 未结 5 1521
情歌与酒
情歌与酒 2020-12-03 13:31

What is the portable way to check whether malloc failed to allocate non-zero memory block?

5条回答
  •  心在旅途
    2020-12-03 14:05

    malloc(n) returns NULL on failure.
    malloc(0) may return NULL.

    To detect failure:

    void* ptr = malloc(n);
    if (ptr == NULL && n > 0) Handle_Failure();
    

    Notes:

    As in OP's case: "... allocate non-zero memory block", often code is such that a 0 allocation request can not occur and so the 0 test is not needed.

    size_t nstr = strlen(some_string) + 1;
    void* ptrstr = malloc(nstr);
    if (ptrstr == NULL) Handle_Failure();
    

    Some systems set errno on failure, but not all. Setting errno due to memory allocation failure is not specified in the C11 spec.

    malloc(n) expects n to be the unsigned type size_t. Using an int n with a negative value will certainly convert to some large unsigned value and then likely fail the memory allocation.

提交回复
热议问题