hharchani
hharchani

Reputation: 81

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.

Upvotes: 3

Views: 1574

Answers (3)

Amr Ayman
Amr Ayman

Reputation: 1159

That's perfect, as long as you're super sure the caller is going to call free to avoid memory leaks .. That's not a big issue on small programs, but when the program gets complex, believe me, you'll be concerned about much more things than freeing a pointer from a supposed-to-be self-contained function ..

But (hands down), there's a much more satisfying solution to this that the standard C Library itself uses. Use a Buffer ! (Claps, Claps)

You know, there is a reason the fgets function for example requires you to provide a character pointer as the first argument, so that it can write to it rather than returning a malloc'd pointer ..

For example ..

#include <ctype.h>
#include <string.h>

void toLower(char *buf, const char *s) {
    for(int i = 0; s[i]; ++i)
        buf[i] = tolower(s[i]);
}
int main(int argc, const char ** argv) {
    const char *s = "ThAt'S a BiG sTrIng";
    char lower_version[strlen(s)];
    toLower(lower_version, s);
    printf("Original Version: %s\nLower Version: %s\n\tTada !\n", s, lower_version);
}

That way, you don't have to worry how you're going to handle the variable in later uses ..
You're leaving this problem to the function caller to deal with.

Upvotes: 2

John Bode
John Bode

Reputation: 123448

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.

Upvotes: 3

Code-Apprentice
Code-Apprentice

Reputation: 83527

This is perfectly fine as long as you call free() somewhere to avoid memory leaks. Part of your program design should be defining the "owner" of each pointer. Such ownership can be transferred, so you should keep track of the owner throughout the lifetime of the pointer. The owner at the time the pointer becomes unused should be responsible for calling free().

Upvotes: 1

Related Questions