Ryan Foley Ryan Foley - 1 year ago 56
C Question

Allocating memory to a struct member pointer in C

I have a structure with a member that I need to pass to a function by reference. In that function, I'd like to allocate memory & assign a value. I'm having issues somewhere along the line - it seems that after the code returns from

, the memory that I had allocated & the values that I assigned go out of scope (this may not be exactly what is happening, but it appears to be the case).

#include <stdio.h>
#include <stdlib.h>

typedef struct myStruct_t
char *myString;
} myStruct;

void allocateMemory(void *str);

int main(void) {
myStruct tmp = {
.myString = NULL
myStruct *p = &tmp;

//allocateMemory(&(p->myString)); //also tried this

printf("%s", p->myString);

return 0;

void allocateMemory(void *str)
str = malloc(8);

((char *)str)[0] = 'a';
((char *)str)[1] = 0;

If I print the value of
inside of
, the 'a' is successfully printed, but if I attempt to print
, my string is empty.

Can anyone tell me what I'm doing wrong?

Answer Source

You need to pass address of the structure member and then you can change (aka allocate memory) to it. In your version of the function, you are not taking a pointer not reference of a pointer, so you can change the content of memory referenced by the pointer but not the pointer itself.

So change your function to

void allocateMemory(char **ret_str)
    char *str = malloc(8);

    str[0] = 'a';
    str[1] = 0;
    *ret_str = str;

And then call it as