Italo Grossi
Italo Grossi

Reputation: 95

Is it safe/correct to return a string from a function that had its memory allocated on the same function?

I understand that if I want to return a string literal or an array from a function I should declare it as static so the contents don't "die" when the called function is returned.

But my question is, what about when I allocate memory using malloc inside a function?

In the following function:

char * getLine() {

    char *line = (char *) malloc(10 * sizeof(char));

    printf("Enter a string: ");
    fgets(line, 10, stdin);

    return line;
}

The memory address returned from this function is still safe even after the function getLine returns?

Upvotes: 1

Views: 103

Answers (3)

HonkyTonk
HonkyTonk

Reputation: 2039

As others have stated, returning a pointer to dynamically allocated memory is fine.

But, as also has been stated, the caller now has to keep track of when that memory is no longer needed and deallocate it.

In cases like this one, it is often wiser to let the caller supply the memory to be filled since this solves the problem with ownership of memory and it adds the benefit of being able to fill any (pre)allocated chunk of memory with data.

So, your function might look like this:

char* get_line(char* dst, int size) {
  printf("Enter a string: ");
  fgets(dst, size, stdin);

  return dst;
}

Now you can call this function in a loop or whatever matches your needs and the function itself only has two side effects (apart from writing to memory): writing to the terminal and reading from it. This is good.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

I understand that if I want to return a string literal or an array from a function I should declare it as static

That's not exactly right: although declaring it static would fix the problem, so would allocating it in the dynamic memory, i.e. malloc/calloc/realloc/strdup/etc. So the answer is "yes, returning malloc-ed memory from a function is perfectly safe". Of course the caller that receives dynamic memory must take care of free-ing it when it is no longer needed.

EDIT : (in response to comments) In fact, using static may be inferior in some contexts, because the buffer would remain shared. For example, if you decide to make a list of user-entered strings, you would be forced to make copies in the caller. In addition, using static would make your function non-reentrant, which is harmful in concurrent environments.

Upvotes: 4

John Chadwick
John Chadwick

Reputation: 3213

Yes, but then something else has to call free on the same pointer, or the memory will remain allocated until the process exits.

Upvotes: 1

Related Questions