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_mallocthat serves as a "wrapper" formalloc. When we callmy_mallocand ask it to allocatenbytes, it in turn callsmalloc, tests to make sure thatmallocdoesn't return a null pointer, then returns the pointer frommalloc. Havemy_mallocprint an error message and terminate the program ifmallocreturns 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.