You want to allocate space for both length and string in the same memory block. It may be what you intended with your structure, but you have reserved space only for a pointer to a string.
A space containing string characters should be allocated.
For instance:
typedef struct
{
int num_chars;
char string [];
} my_string_t;
my_string_t * alloc_my_string (char * src)
{
my_string_t * p = NULL;
int N_chars = strlen (src) + 1;
p = malloc (N_chars + sizeof (my_string_t));
if (p)
{
p-> num_chars = N_chars;
strcpy (p-> string, src);
}
return p;
}
In my example, to access a pointer to your string, you access a stringmember my_string_t:
my_string_t * p = alloc_my_string("hello free store.");
printf("String of %d bytes is '%s'\n", p->num_chars, p->string);
, , , . , , , .
:
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
| 00 | 00 | 00 | 11 | 'h'| 'e'| 'l'| 'l'| 'o'| 20 | 'f'| 'r'| 'e'| 'e'| 20 | 's'| 't'| 'o'| 'r'| 'e'| '.'| 00 |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
^^ ^
|| |
p| |
p->num_chars p->string
, p->string , , ( 32-, ) .
, C :
typedef struct
{
int num_chars;
char string[0];
} my_string_t;
, , C99.
:
typedef struct
{
int num_chars;
} mystr2;
char * str_of_mystr2(mystr2 * ms)
{
return (char *)(ms + 1);
}
mystr2 * alloc_mystr2(char *src)
{
mystr2* p = NULL;
size_t N_chars = strlen(src) + 1;
if (N_chars num_chars = (int)N_chars;
strcpy(str_of_mystr2(p), src);
}
return p;
}
printf("String of %d bytes is '%s'\n", p->num_chars, str_of_mystr2 (p));
, p->string, str_of_mystr2(). , , , .
size_t, , . , INT_MAX, . int, assert(p->num_chars >= 0); -. , , assert(p->num_chars < UINT_MAX / 2); , , .
, , , UINT_MAX/2, .