I wonder where the literal string that str
points to is allocated, given that (I assume) malloc only makes room for the pointer into the Heap.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int a;
char* str;
} Bar;
int main(int argc, char *argv[])
{
Bar* bar_ptr = (Bar*)malloc(sizeof(*bar_ptr));
bar_ptr->a = 51;
bar_ptr->str = "hello world!";
printf("%d\n", bar_ptr->a);
printf("%s\n", bar_ptr->str);
return 0;
}
CodePudding user response:
As already pointed out the string is stored in a read-only data segment. You can print the address where the string is stored (in hexadecimal format) like that:
printf("0x%p\n", bar_ptr->str);
CodePudding user response:
Correct - all your struct type stores is the address of the first character in the string. The string contents are stored "somewhere else" - in a string literal, in another dynamically-allocate block, in a static
or auto
array, etc.
You could declare everything auto
:
void foo( void )
{
char aStr[] = "this is not a test";
Bar barInstance;
barInstance.a = 51;
barInstance.str = aStr;
...
}
You could allocate everything dynamically:
Bar *barInstance = malloc( sizeof *barInstance );
if ( barInstance )
{
size_t size = strlen( "This is not a test" );
barInstance->str = malloc( size 1 );
if ( barInstance->str )
strcpy ( barInstance->str, "This is not a test" );
...
/**
* You must free barInstance->str before freeing
* barInstance - just freeing barInstance won't
* free the memory barInstance->str points to,
* since that was a separate allocation.
*/
free( barInstance->str );
free( barInstance );
}