692 B
692 B
1. Having to check the return function of
malloc
(or any other memory allocation function) each time we call it can be an annoyance. Write a function namedmy_malloc
that serves as a "wrapper" formalloc
. When we callmy_malloc
and ask it to allocaten
bytes, it in turn callsmalloc
, tests to make sure thatmalloc
doesn't return a null pointer, then returns the pointer frommalloc
. Havemy_malloc
print an error message and terminate the program ifmalloc
returns a null pointer.
void *my_malloc(size_t n) {
void *p = malloc(n);
if (p == NULL) {
printf("Failed to allocate memory");
exit(EXIT_FAILURE);
}
return p;
}
2.