int main()
{
cout<<"Enter n";
cin >> n;
int * a = new int[n];
a = foo(n);
free(a);
return -1;
}
int * foo(int n)
{
int * a = new int [n];
if(!a) // what should I return here if allocation of a fails
{}
free(a);
}
In the code above I am trying to catch the return value of an function from main, the return type of the function is a pointer . However I am allocating memory dynamically . So , what should I return if my memory allocation fails … any special symbol like NULL .
P.S – Its a very basic question and could not formalize my question to any succinct form for to search over Google.
Edit: Thanks all of you guys . I have solved my problem .
It is a custom to return NULL in case of allocation failure from functions which allocate their own memory and return pointer to it. See for example
strdup(). Note that operatornewthrowsstd::bad_allocif it fails to allocate memory, so you may need to catch this if you want to return NULL or alternatively, you can letstd::bad_allocpropagate out of the function.Note however, that it is not always wise to return such pointers since it raises the issues of ownership and increases the likelihood of memory leaks.
You may find that sticking to the RAII idiom makes your code easier to reason about and less error prone. One consequence of RAII idiom is that allocation and deallocation are done by the same code unit.
In your particular situation you allocate the array in
main()so you may pass the pointer to it tofoo()and deallocate memory also inmain().Also, if you use
newto allocate, you should use a proper version ofdeleteto deallocate (heredelete[]since you allocated an array). You usefree()to deallocate memory allocated withmalloc()and friends.