Beginner question. I wanted to make a very simple function that checked whether a pointer (freshly allocated) was null or not. If null, shut down with a message, else return the pointer, was the idea. But the compiler wouldn't let me do it without a perverse "return NULL" after the call to exit(). See below.
Does anyone know of a way around this? The compiler was complaining that not all paths returned a value.
Thanks,
Lars
1 2 3 4 5 6 7 8 9 10
void *zc(void *ptr) // pointer sanity check for malloc / new
{
if (ptr == NULL)
{
printf("Can't allocate memory!\n");
exit(1);
return NULL;
}
return ptr;
}
Also, update your compiler and library. exit is _Noreturn / [[noreturn]] since C11/C++11. Granted, IMO it's not wrong to expect your compiler to understand this even before C++11: I'd file a bug report with the compiler or library vendor.
I tested this on Compiler Explorer with both GCC and Clang, with -Wall and -Wextra, with and without optimizations, and it doesn't seem to produce this warning for any version.