Do we need to free memory allocated by malloc inside user defined function? isn't that automatically freed when the function returns? suppose if we free using fee(), does it have any affect (need not be reflected in output)?
Do we need to free memory allocated by malloc inside user defined function? isn't that automatically freed when the function returns? suppose if we free using fee(), does it have any affect (need not be reflected in output)?
No, not if you return a reference to the memory so that you can free it later on when you are done.
No
It does if you are trying to use the free'd item after, you would use free when you don't need the object anymore.
but the memory occupied by other variables declared locally inside the user defined function can be used for other purpose once the funcion is returned. Doesnot this happen to allocated memory too which is a pointer type variable. After the function returns, cant the memory pointed by the pointer used as a free memory for new memory allocation and variables.
I think if we return a pointer to the meory allocated in user defined function we cant access it form outside sicne the scope of memory allocated inisde function is local. is it not so?
The pointer is valid once malloc'd, even after you leave the function - it is not local (on the heap instead). HOWEVER, if it pointed to a local variable, then that pointer, although perfectly valid, should NOT be used, because what it's pointing to, is no longer valid.
The funny thing is, those local variables that are no longer valid, are still there on a little used system, for awhile. BUT DON'T COUNT ON IT!!
That's the Golden Rule of returning addresses - never return the address (pointer), of a local variable.
I don't believe it's RIGHT next to the stack - the OS saves that to detect errors, I believe.
When I've played with it, the local variables that were not valid anymore, were still there, as long as the system was not busy. Once it got busy, those values were overwritten within a few seconds. On a server like Windows 2008 which I was just testing out last week, it's different though. There, the administrator can set the memory to be "scrubbed" on a few different schedules.
The stack does not get cleaned up by the OS. It's a dedicated area of memory for that process. Things don't get overwritten until you enter another function and use more local variables.
As each process has its own stack area, there is nobody who will use yours.