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!