I was asked this in a recent interview, basically writing a function to combine the functionality of free and assigning null. I answered in the following manner:
void main()
{
int *ptr;
ptr = new int;
ptr = newdelete(ptr);
}
(int*) newdelete (int *ptr)
{
delete(ptr);
return NULL;
}
So after execution, the ptr
local to main
will hold the null value as I am returning it from the newdelete
function. If I had just assigned NULL
in the newdelete function, the ptr
local to newdelete
would be nulled and not the ptr
local to main
.
I think my solution was correct, the interviewer accepted it too. However, he was expecting some other answer. He was insisting I do not return the NULL
from the function and still achieve the desired result.
Is there any way to accomplish that? All I can think of is passing another argument which is the pointer to the pointer ptr
local to main
, but I don't see why it's better than what I did!
After using free(ptr) , it's always advisable to nullify the pointer variable by declaring again to NULL. e.g.: free(ptr); ptr = NULL; If not re-declared to NULL, the pointer variable still keeps on pointing to the same address (0x1000), this pointer variable is called a dangling pointer.
We can use nullptr to explicitly initialize or assign a pointer a null value. In the above example, we use assignment to set the value of ptr2 to nullptr , making ptr2 a null pointer. Use nullptr when you need a null pointer literal for initialization, assignment, or passing a null pointer to a function.
Setting message to NULL after it is freed eliminates the possibility that the message pointer can be used to free the same memory more than once.
Is there any way to accomplish that??
template <typename T> void safeDelete(T*& p){
delete p;
p = 0;
}
int main(int argc, char** arv){
int * i = new int;
safeDelete(i);
return 0;
}
I guess he was expecting something like:
void reset(int*& ptr)
{
delete(ptr);
ptr = NULL;
}
An even cleaner solution would have been to use a boost::shared_ptr<>
and to simply call ptr.reset()
. However, I suppose this wasn't an option.
If the requrement wasn't to write a function, you could always write a macro that would do it for you as well:
#define my_delete(x) { delete x; x = NULL; }
Of course, calling it like this will get you into all sorts of trouble:
my_delete(ptr++)
So, I think I prefer the non-macro way.
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