>so prelude, which works?
You can malloc the pointer in main and then pass it to the function (freeing it in main when you're done), or you can malloc the pointer in the function and return it to main (also freeing it in main when you're done):
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void test1 ( char *p )
{
strcpy ( p, "test" );
}
char *test2 ( void )
{
char *p = malloc ( 5 );
strcpy ( p, "test" );
return p;
}
int main ( void )
{
char *p1;
char *p2;
p1 = malloc ( 5 );
test1 ( p1 );
puts ( p1 );
free ( p1 );
p2 = test2();
puts ( p2 );
free ( p2 );
return 0;
}
The former is recommended over the latter because it keeps the allocation and deallocation at the same level. It's harder to forget to free when you can look for a malloc in the same function.