Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple c malloc

Tags:

c

malloc

this doesn't work:

void function(char* var)
{
    var = (char*) malloc (100);
}

int main()
{
    char* str;
    function(str);
    strcpy(str, "some random string");
    printf("%s\n", str);

    return 0;
}

this does:

void function(char* var)
{
    //var = (char*) malloc (100);
}

int main()
{
    char* str;
    //function(str);
    str = (char*) malloc (100);
    strcpy(str, "some random string");
    printf("%s\n", str);

    return 0;
}

Why?

like image 421
nunos Avatar asked Dec 31 '25 07:12

nunos


1 Answers

You have to pass the address of the pointer to assign the address you want inside the function, otherwise you are just passing a copy of it:

void function(char** var)
{
    *var = malloc (100);
}

int main()
{
    char* str;
    function(&str);
    strcpy(str, "some random string");
    printf("%s\n", str);

    return 0;
}
like image 55
Khaled Alshaya Avatar answered Jan 01 '26 22:01

Khaled Alshaya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!