简体   繁体   中英

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 allocateMemory , 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);
    //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 str inside of allocateMemory , the 'a' is successfully printed, but if I attempt to print p->myString in main , my string is empty.

Can anyone tell me what I'm doing wrong?

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

allocateMemory(&p->myString)

An alternative way of writing the same function Rohan did, eliminating the need to define any new variables:

void allocateMemory(char **str, size_t size) {
    *str = malloc(size);
    (*str)[0] = 'a';
    (*str)[1] = '\0';
}

Note that I pass a size parameter to justify using malloc() in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM