c - when the memory is cleared on stack for a local function? -


i want know when memory cleared in stack allocated local function calls. have seen in video tutorial when function call returned main memory allocated local function cleared. have few questions on below program, please explain.

#include<stdio.h>  void print(){ printf("testing \n"); }  int* sum(int* a, int* b){ int c = *a + *b; return &c; }  int main(){ int a=3,b=2; int *ptr = sum(&a,&b); print();           printf("sum is: %d",*ptr); return 0; } 

when run above program, printing garbage value expected. if comment "print()" function in main , run program printing correct value of sum.

  1. is mean though execution of local function completed in stack, until there function call stack, previous allocated memory not cleared ?

  2. if remove "printf" statement in "print()" , keep "print()" call in main, see result of sum normal. why didn't overwrite memory in stack?

c has no stack, word stack not mentioned in standard (c89, c99 or c11). implementation may use stack provide behavioural aspects of c abstract machine it's abstract machine standard specifies.

so, when stack cleared (assuming exists), that's that's totally implementation. doing undefined behaviour, accessing object after lifetime has ended, results can implementation chooses.

as why can access items after lifetime has ended specific implementation, it's because entering , exiting function doesn't clear stack, adjusts stack pointer (a lot more efficient having clear memory well).

so, unless overwrites what's @ memory location (such subsequent call printf), it'll remain @ whatever last set to.

by way of example, here's sample prolog code function:

push  ebp       ; save frame pointer. mov   ebp, esp  ; set frame pointer current stack pointer. sub   esp, xx   ; allocate xx space frame. 

and equivalent epilog:

mov   esp, ebp  ; restore stack pointer. pop   ebp       ; previous frame pointer. ret             ; return. 

note neither allocation of space (sub in prolog) nor deallocation of (mov in epilog) clears memory it's using.

however, stated, it's not should rely on.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -