Returning a pointer to something that was created on the stack is a bad idea as it will be destroyed when it goes out of scope, so your pointer will point to either nothing in particular, or something owned by another part of your program (which leads to unpredictable and undefined behavior), unless the variable was static (which probably isn't what you want). Here is an example of what not to do:
Code:
int* foo( )
{
int x = 3;
return &x; // Once the function returns, x goes out of scope, so what your pointer points to is unpredictable.
}
You can, however, return a pointer to something that was created on the heap without fear of it going out of scope. You must, however, make sure that the memory allocated is later freed.
Code:
int* foo( )
{
int* p = new int;
*p = 3;
return p;
}
void bar( )
{
int* r = foo( );
// ...
delete r;
// The following, however, is a memory leak.
foo( ); // Now, nothing points to the allocated memory, so it cannot be freed.
}