Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

malloc is the devil

Name: Anonymous 2007-11-19 11:37

hay, /prog/.

I'm creating a function which, given a pointer as an argument, creates memory for it (malloc) and then fills it with data (using a struct). This doesn't work, seemly because I'm doing the malloc inside the function itself, if I call malloc to the pointer in main, before calling the function, everything works fine.

Does this mean I can't pass a pointer to a function, malloc it inside there and be on my merry way when the function returns? Ouch. halp.

Name: Anonymous 2007-11-19 14:24

>>1
Try:

struct foo
{
    int bar;
};

main()
{
    struct foo* f;
    baz(&f);
    f->bar = 1;
    // etc
}

void baz(struct foo** f)
{
    *f = malloc(sizeof(foo));
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List