Stupid compiler rules

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;
}
Show a minimal, complete example that reproduces the message.
And say what compiler & version you are using.
Last edited on
Does anyone know of a way around this? The compiler was complaining that not all paths returned a value.

this is a warning on every compiler I know. If you have set warnings=errors, then its an error.

// pointer sanity check for malloc / new
new never returns NULL.

Ugh, it's 2020 and I'm still saying this.

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.
Last edited on
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.

https://godbolt.org/z/1W9o3f
Last edited on
new never returns NULL
What about second breakfast std::nothrow?
Last edited on
Topic archived. No new replies allowed.