At 2004-03-04 16:07:16 +0800, [EMAIL PROTECTED] wrote: > > Very true when the function returns the stack is emptied and all local > variables are deleted.
That's not true, and it's a very misleading way of thinking about this situation. Yes, automatic variables (as C calls them) are allocated on the stack, and are not visible outside their defining lexical scope. But when the function returns, neither is the stack "emptied", nor are automatic variables "deleted". The variables just cease to be visible, but this is not as a result of some active intervention by the system or compiler. There is no "deleting" happening (in C, anyway; in C++, destructors get called on scope exit). I mention this in particular because the stack is usually _not_ emptied. The stack pointer is moved, but whatever was on the stack is usually not disturbed. It's no longer on the stack, but that's by definition, not by any explicit destruction. (This is why automatic variables in C have to be initialised before use. When they're created on the stack, there is no way of telling what might have been there before.) > But the pointer is made on the heap not the stack! So you will have to > "delete" the pointer manually. That's not true either, in this case the "char * ptr" is also automatic. Furthermore, returning it would not cause a memory leak (since there is no malloc() allocation happening). > ptr=string; > printf("PtrAddr=%x\n",ptr); //Print the address of the ptr > //not the contents > } > > As you will see the above two values are equal. Of course the two values are equal. That's not the point. The point is that returning the address of an automatic variable is incorrect, and the compiler should warn about such things. If you do "return string", gcc does warn you, but I expect detecting "ptr=string; return ptr" is too expensive, or opens up too many hard-to-detect equivalents. -- ams _______________________________________________ ilugd mailinglist -- [EMAIL PROTECTED] http://frodo.hserus.net/mailman/listinfo/ilugd Archives at: http://news.gmane.org/gmane.user-groups.linux.delhi http://www.mail-archive.com/[EMAIL PROTECTED]/