Returning pointer to local variable

Hi,
we should avoid returning a pointer to local variable. If one wants to do that then either variable has to be declared static or varable has to be allocated dynamically. In later case calling function should take care of deallocating the variable to avoid memory leaks.
Can anyone tell me why it works in case of dynamically allocation and static declaration and why not in case of simple local variable?