Why return malloc'd char array not work, but local char array does?
Inside a function, I create a char array which I pass to a library function that fills it with a value. I then pass this back to the caller. When I do it by creating an array with malloc (and then freeing it outside the function), it only fills the array with the first 3 characters. When i create it as a local array, it works (and simply warns me I'm passing a local array back out).
Code:
//This does NOT Work:
char* getStringWithMalloc(...elided...)
{
char* data = ( char* ) malloc( 256 * sizeof( char ) );
fillArray( data );
return data;
}
//This DOES work:
char* getString(...elided...)
{
char data[256];
fillArray( data );
return data;
}
int main(...)
{
//Does not work, only grabs first three characters
char* value = getDataWithMalloc(...);
printf( value );
free( value );
//This DOES work
printf( getDataWithMalloc(...) );
}