Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack frame memory allocation

Tags:

c

stack

Like every function is put on a stack frame for its execution and it is flushed after its completion. So, any local variable wont be available to other functions. But then how are we able to return a local variable to the caller?

int pickMin( int x, int y, int z ) {
 int min = x ;
 if ( y < min )
    min = y ;
 if ( z < min )
    min = z ;
 return min ;   }

The above code works fine. However the in the below code, compiler does give a warning message- "warning: function returns address of local variable [-Wreturn-local-addr] return a; " but it prints a garbage value at the end, which I think is fine because the variable has already been flushed. But why didn't that happen in the ABOVE program?! I mean, it should also have returned me a garbage value.Moreover, I know that the problem in the below code can be solved using malloc, and then returning that value. :)

int *returnarray(){
 int a[10]; int i;
  for(i=0;i<10;++i){
     a[i] = i;
 }return a;}   
like image 801
Marwadi Avatar asked Dec 15 '22 20:12

Marwadi


2 Answers

C passes everything around by value. In your first snippet, return min returns an int variable. Its value is returned. The second snippet consists of return and an array name, which decays into a pointer.
The value that is returned, is the memory address of a local variable. The function where this variable existed has returned, though, and accessing the memory that this function used then invokes undefined behaviour.

The way to handle this kind of situation (ie: needing to return an array) is either by passing the target array to the function as an argument, or by allocating the memory using malloc and returning that pointer.
Heap memory is a tad slower, more error prone, and requires you to look after it though. Still, here's an example of both approaches
create_fill allocates, assigns and returns a pointer to the heap memory, fill_array doesn't return anything, but expects you to pass an array (which decays into a pointer), and a max length to fill. The advantage being: stack memory doesn't require as much care, and will outperform the heap.

like image 137
Elias Van Ootegem Avatar answered Jan 02 '23 05:01

Elias Van Ootegem


The return statement des exactly that: it copies the value of a variable, and leaves it on top of the stack so the calling function can use it. Now, in C this works for simple values, not for arrays because your "array variable" a is actually the address of its first value only.

like image 24
Jay Avatar answered Jan 02 '23 03:01

Jay