How to correctly check the size passed to malloc() calloc() realloc() as well as their return value?

Viewed 800

If I have understood correctly, it is also important to check that the desired space passed to malloc(), calloc() or realloc() does not exceed the SIZE_MAX constant after the multiplication with the sizeof(desired_type). In order to make sure that does not happen I started to do something like this in my codes:

#define MAX_CHAIN (50)


#ifndef SIZE_MAX
#define SIZE_MAX (~(size_t)0)
#endif

int main(int argc, char const *argv[]){

    char **parsed_string;

    if(MAX_CHAIN > SIZE_MAX/sizeof(char*) || 
    (parsed_string=(char**)malloc(MAX_CHAIN * sizeof(char*)))==NULL){
        printf("%s\n", "Error, cannot allocate memory");
        exit(1);
    }

    /*Otherwise pointer is valid and the execution continues*/


}

So it basically checks for two things:

  1. That the requested memory is not bigger that SIZE_MAX
  2. That the pointer returned by malloc() is valid.

My questions are: Is it a correct to do these checks? Is this considered as good practice or should I use something else instead? Also, can someone explain why the allocation is limited by SIZE_MAX?

2 Answers
Related