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

Pages: 1-

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 11:41

Of course you can do that. But you're probably doing it wrong.

Name: Anonymous 2007-11-19 11:47

lrn2 pass by value. Regardless, a function like that should simply return a pointer, not fuck with one passed in.

Name: Anonymous 2007-11-19 12:08

What? It sounds like you're doing this:

void foo(struct bar * ptr) {
    ptr = malloc(sizeof(struct bar));
    ptr->retarded = 1;
}

int main(void) {
    struct quux * mystruct;
    foo(mystruct);
}


Which is completely retarded.

Name: >>3 2007-11-19 12:26

>>4
I think he tries this:

#include <string.h>

struct howtofillstruct
{
    int charactertofill; /* Or whatever */
};

void create(char *input, size_t size, struct howtofillstruct howtofill)
{
    input = malloc(size);
    if(input)               /* if he does error handling at all */
        memset(input, howtofill.charactertofill, size);
}

int main(void)
{
    char *foo;
    struct howtofillstruct howtofill;

    howtofill.charactertofill = 'A';
    create(foo, 100, howtofill);

    printf("Foo is 0x%x.\n", foo);
    printf("Foo[0] contains %c.\n", foo[0]); /* segfault */

    return 0;
}

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));
}

Name: Anonymous 2007-11-19 14:53

>>6 illustrates the difference between pass by reference and pass by value. +1 experience points.

Name: Anonymous 2007-11-19 15:16

>>7 is a slashdot goon

Name: Anonymous 2007-11-19 16:11

>>7
It's still pass by value.

Name: Anonymous 2007-11-20 7:55

>>9
yes, yes, all it's pass by value.

Name: Anonymous 2007-11-20 7:57

>>9
don't confuse him more

Name: Anonymous 2007-11-20 8:08

ITT I HAVEN'T DISCOVERED A GARBAGE COLLECTOR YET

>>1
It should work, but...
YOU'RE DOING IT WRONG

>>9
Truth; it's particularly easy to see it in C

Name: Anonymous 2010-12-09 15:35

<

Name: Anonymous 2010-12-10 11:26


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