0

Possible Duplicate:
returning a local variable from function in C

The more I think about this, the less I am sure why this is not such a good idea... The compiler complains about having an auto variable from inside the function return to the caller. For instance:

char * foo() {
   char bar[11];
   fgets(bar, 10, stdin);
   return bar;
}

Versus:

char bar[11];
char * foo() {
   fgets(bar, 10, stdin);
   return bar;
}

I am probably not making much sense. I don't quite understand the problem of having a pointer declaration inside, would the the caller simply not just assume the memory address?

Community
  • 1
  • 1
Serguei Fedorov
  • 7,763
  • 9
  • 63
  • 94

3 Answers3

1

In your first example, the array bar is local to the function, so that it doesn't exist any more when the function returns. Hence the resulting pointer isn't likely to point at anything useful, because what it used to point at doesn't exist anymore.

Kos
  • 70,399
  • 25
  • 169
  • 233
  • 1
    What's worse, is that during simple testing, the array probably will still exist for a little bit, so it might pass testing most of the time. Then when the application gets a little weight to it, the bug will show up. But in your mind, you will have validated that method already and will instead look somewhere else. – corsiKa Jul 09 '12 at 21:43
0

The first example is completely wrong. You create memory space and write there inside function and return pointer to it, so you're returning pointer to a non-existent memory segment. This memory will be freed after returning from function. Second example is correct, but you should avoid using global variables if possible.

Edit: If you want memory to be usable outside the function after returning pointer to it, use dynamic memory allocation (check calloc function).

Wookie88
  • 33,079
  • 4
  • 27
  • 32
0

bar, for all intents and purposes, ceases to exist when your function returns. It is allocated with automatic storage duration and attempts to read from that memory later result in undefined behavior. Since a stack is typically used, how would you imagine keeping that data around in a valid state once the function has returned?

Instead, you can take a char* as input to the function, along with the size of the memory block it refers to, and fill that buffer for the caller, i.e.,:

void foo(char *buf, buf_size) {
   fgets(buf, buf_size, stdin);
}

This is very common and idiomatic in C. Look at what fgets is doing. It is asking you, the caller, to supply a buffer to fill. This avoids confusion on who is responsible for deallocating the memory returned from a function (which you would have to document if your function returned a pointer to dynamically allocated memory).

BTW, fgets reads num-1 characters and null terminates for you, so just pass the size of the buffer, no need to pass size-1 as you are currently doing.

Ed S.
  • 122,712
  • 22
  • 185
  • 265