0

I'm studying for exams right and i've come across this question:

What is the crucial error in this code?

int *numbers(int a, int b)
  {
     int array[2];
     array[0] = a * b;
     array[1] = a + b;
     return array;
  }

Now, I don't have much C experience but I don't see a crucial error in this code at all. Maybe I'm being a moron and just overlooking something obvious. The only thing I can see is memory hasn't been allocated using malloc but I don't see that a big problem.

Any help is appreciated!

Elviii
  • 21
  • 6
  • 9
    What happens to `array` when the function exits? What does that mean for the caller that tries to use the result of this function? – Paul Roub May 19 '14 at 16:56
  • 1
    You are returning a pointer that will be invalid after the function returns. – R Sahu May 19 '14 at 16:56
  • "memory hasn't been allocated using malloc but I don't see that a big problem" It is. EIther memory is allocated in the stack, and is lost when function returns, (as here), either is allocated in heap (with malloc / new) – leonbloy May 19 '14 at 16:57
  • 1
    why are people downwoting? – Andro May 19 '14 at 16:57
  • 1
    @CandyMan Because it's a duplicate, probably. I can't find a link right now, though. Anyway, OP's gaining from pity-upvotes anyway. – sashoalm May 19 '14 at 17:00
  • 1
    @sashoalm Well 'probably'. One should provide some hard evidence before blindly downvoting. – Andro May 19 '14 at 17:01
  • No, he shouldn't, downvotes are discretionary, it says so in the FAQ - you're free to downvote if you feel the question should be downvoted. You don't have an obligation to defend or explain them. Same with upvotes. – sashoalm May 19 '14 at 17:02

4 Answers4

5

The most basic problem here is that array ceases to exist as soon as numbers() returns. The returned pointer is pointing to space that will likely be overwritten in just a moment.

Phil Perry
  • 2,126
  • 14
  • 18
3

The variable array will disappear when the function returns, but you have returned a pointer to its place in memory.

Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75
3

You are basically returning garbage, because array will go out of scope after return. If you make array static everything will be OK.

Andro
  • 2,232
  • 1
  • 27
  • 40
  • Making the array static is malpractice. Since there is only one instance of static array calling the function in many different places will result in a pointer to the same memory region. Function won't be thread-safe and reentrant too. Baaaad practice. – ezaquarii May 19 '14 at 23:42
  • I agree. But just for the argument sake, it would work. Of course, one should not use suck practice in real world. – Andro May 20 '14 at 12:58
0

If memory WAS allocated with malloc, then the function would be valid. Once the function exits, any memory that was allocated within the scope of the function (stack) is no longer valid.

theorifice
  • 670
  • 3
  • 9