#include <stdio.h>
void get( char ** msg )
{
*msg = strdup( "This string will survive beyond this function." );
}
void get_bad( char * msg )
{
// The memory in msg will be lost after exiting this function.
msg = strdup( "Not seen outside this function" );
}
int main()
{
char *msg = NULL;
get( &msg );
if( msg )
{
printf( "Got this message: '%s'\n", msg );
free( msg );
msg = NULL;
}
else
{
printf( "We'll get here if the memory allocation in 'get' failed.\n" );
}
get_bad( msg );
if( msg )
{
printf( "We'll never get here, but, anyway: '%s'\n", msg );
free( msg );
}
else
{
printf( "Didn't get a message, as expected.\n" );
}
return 0;
}