Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using malloc inside a function and return local pointer

Is there any problem in doing something like this in C

char* wrap(char *inp) {
    char *newstr;
    newstr = (char *)malloc( sizeof(char) * 4);
    newstr[0] = 'A';
    newstr[1] = inp[0];
    newstr[2] = 'B';
    newstr[3] = '\0';
    return newstr;
}

Basically I want to know that is there problem in using malloc inside a function and returning local variable.

like image 407
hharchani Avatar asked Sep 24 '26 01:09

hharchani


1 Answers

You're not returning a local variable; you're returning the value stored in a local variable.

This code is fine (although the cast on malloc is unnecessary); it's a somewhat common pattern to allocate memory in one function and free it in another.

like image 144
John Bode Avatar answered Sep 25 '26 22:09

John Bode



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!