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?
Answer
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.
No comments:
Post a Comment