2

It seems as a good programing practice to check each time after using malloc/calloc if an address was asagin.

Is there an option to create a function to check if the allocation succeed? as we cast we cast the type of the point each time, so the function will not know which pointer type is it.

For example:

newUser -> name = (char*)malloc(NAME_LENGTH*sizeof(char));
    if (newUser -> name == NULL){
        printf("Allocation of newUser failed\n");
        exit(1);
    } 

User *newUser = (User*)malloc(sizeof(User));
    if(newUser == NULL){
        printf("Allocation of newUser failed\n");
        exit(1);
    }

Can a function be created that gets newUser and newUser -> name and will exit if allocation failed?

gbox
  • 809
  • 1
  • 8
  • 22
  • 1
    [The cast is unnecessary in C](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Your function can simply return a `void *` if the `malloc` succeeded. – user3386109 Dec 27 '18 at 20:06

1 Answers1

5

First, don't cast the return value of malloc as it can hide other errors.

There's no problem wrapping malloc in a function that will do the null check for you. Since malloc takes a size_t and returns a void * your wrapper function should do the same. For example:

void *safe_malloc(size_t s)
{
    void *p = malloc(s);
    if (!p) {
        perror("malloc failed");
        exit(1);
    }
    return p;
}

Then you can use this function anyplace you use malloc without having to explicitly do a NULL check.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • I personally prefer to replace `perror("malloc failed"); exit(1);` with `fprintf(stderr, "malloc(%zu) failed: %s.\n", s, strerror(errno)); exit(EXIT_FAILURE);` as the latter tells me how large an allocation was attempted. I admit: I've created code that failed because I calculated `s` wrong.. but the more informative error message helped me fix it. (The `exit()` bit is irrelevant to that, I just prefer the more informative-to-us-humans form.) – Nominal Animal Dec 28 '18 at 03:51