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;
}
If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.
In other words, a return call can also be used to terminate procedures and anonymous code blocks without returning a value (as a function would) to the caller. So this is why a function will compile without an error when missing a return.
A method with a void return type will work fine when you omit the return statement.
If you want to return a null function in Python then use the None keyword in the returns statement.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With