C Help? Memory allocation & pointers

AgentEL

Golden Member
Jun 25, 2001
1,327
0
0
I know this is bad:

int * f1( void )
{
int j = 999;

return &j;
}

and this is good:

char * f2( void )
{
char * array;

array = (char *) malloc(8);

return array;
}

But is the following allowed?

char * f3 ( void )
{
char * array2;

array2 = f2();

return array2;
}

void main ( void )
{
char* array3 = f3();

printf("%c\n", array3[1]);

return;
}

Will the memory pointed by array2 still be valid after f3 returns? I would think it would be since you malloc()'ed memory for the array. But, I also think it wouldn't because array2 was a local variable within f3.

Any help?
 

Templeton

Senior member
Oct 9, 1999
467
0
0
It would be valid, you are not returning the address of a variable in the functions stack frame like in the first case, but rather are returning the address of dynamically allocated memory. When you return array2, you are returning its value, which is an address to dynamically allocated memory, you are not returning the address of the array2 pointer itself. Its the same as this:

char f4(){
char c = 'a';
return c;
}

You return the value in the instance variable, not the address of data that will be lost on the functions return. Hope this is clear.