I need a way to return out of a function without having to return the "return type"

Viewed 162

I have a function that allocates memory and then returns the pointer to that memory address. I'm allocating an array of char, the argument that they pass into the function will be the array size. Now the problem is that if they pass 0 as the argument for the size to dynamically allocate, then I want to exit/return out of that function, but the function itself returns a char * so I am not able to do something like return -1;, how would I go around this, while at the same time keeping the function and doing logic to allocate the memory in there? Is there a way?

char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
    if (x == 0)
        return ;
    char *mem{ new char[x] };
    return mem;
}
5 Answers

The correct way to signal that a pointer doesn't point to valid memory is with a nullptr. So your return statement in the case that the memory allocation fails would simply be:

return nullptr;

Of course, the caller of the function needs to make sure that the returned pointer is not nullptr before they try to dereference it.

The canonically correct way to do this given that the input parameter must be an int is either:

char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
    if (x <= 0)
        throw std::bad_alloc();

    return new char[x];
}

or

char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
    if (x <= 0)
        return nullptr;

    return new(std::nothrow) char[x];
}

Depending on if you want it to throw an exception or return nullptr on error. I recommend you pick one and not mix them for consistency

The common practice would be to return nullptr:

char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
    if (x == 0)
        return nullptr; // here!
    char *mem{ new char[x] };
    return mem;
}

The general consensus is to return NULL in C or nullptr in C++. Its value is 0 and can be cast to an address (which itself is actually an integer).

Try this:

char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
    char *mem{ new char[x] };
    return mem;
}

You will be allocating memory for a zero length char.
Alternatively or If it doesn't work : Throw an error:

char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
    if (x <= 0)
        throw std::length_error("Memory size too small (cannot be 0 or smaller)");
    char *mem{ new char[x] };
    return mem;
}

or return a nullptr:

char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
    if (x == 0)
        return nullptr;
    char *mem{ new char[x] };
    return mem;
}
Related