Traduisez - Übersetzen - Traduzca - Traduza - Tradurre - Translate

VanLUG Email Archive

VanLUG Mailing List
Re: Memory allocation under Linux

New Message Reply About this list Date view Thread view Subject view Author view

Ted Powell (ted@eslvcr.fireplug.net)
Fri, 15 Jan 1999 13:43:53 -0800


On Fri, Jan 15, 1999 at 01:31:12PM -0800, Shane Wegner wrote:
> [...]
> I have a few questions with Memory allocation under Linux and am hoping
> someone here has some experience with it. In particular malloc(2) and
> free(2) questions. In the following function, does s free itself?
>
> int test(void) {
> char *s;
> s = malloc(1024);
> return 0;
> }

The memory for s is allocated on the stack at function entry time, and
is automatically freed when test() exits. The memory that you allocated
with the call to malloc() is a different matter. Keeping track of it is
up to you. Tuum est, as they say in westernmost Point Grey.

Nothing is done when test() exits with any char* value you may have
stored in the variable s. When you execute the assignment
> s = malloc(1024);
nothing goes into s but a value of type char*. There is nothing to
record where you got that value of type char*. For that matter, the
code which frees automatic variables on function exit doesn't even know
that s is of type char*. Typically, that code is a single instruction,
restoring the calling function's frame pointer from the stack.

One of the early C gurus remarked that C gives you all of the power, and
all of the safety features, of a chainsaw.

-- 
ted@psg.com  http://psg.com/~ted/  (Ted Powell)
Reality is that which, when you stop believing in it, doesn't go away.
                           --Philip K. Dick


New Message Reply About this list Date view Thread view Subject view Author view

This archive was generated by hypermail 2.0b3 on Fri 15 Jan 1999 - 13:44:21 PST