Tuesday, April 19, 2011

Return by address

Returning by address involves returning the address of a variable to the caller. Just like pass by address, return by address can only return the address of a variable, not a literal or an expression. Like return by reference, return by address is fast. However, as with return by reference, return by address cannot return local variables:
int* DoubleValue(int nX)
{
int nValue = nX * 2;
return &nValue; // return nValue by address here
}

As you can see here, nValue goes out of scope just after its address is returned to the caller. The end result is that the caller ends up with the address of non-allocated memory, which will cause lots of problems if used. This is one of the most common programming mistakes that new programmers make. Many newer compilers will give a warning (not an error) if the programmer tries to return a local variable by address — however, there are quite a few ways to trick the compiler into letting you do something illegal without generating a warning, so the burden is on the programmer to ensure the address they are returning will be to a valid variable after the function returns.
Return by address is often used to return newly allocated memory to the caller:

int* AllocateArray(int nSize)
{
return new int[nSize];
}
int main()
{
int *pnArray = AllocateArray(25);
// do stuff with pnArray
delete[] pnArray;
return 0;
}

No comments:

Post a Comment