Re: a quick malloc question
From: Jerry Feldman (gaf-noSPAM_at_blu.org)
Date: 09/27/03
- Previous message: Paul Pluzhnikov: "Re: Got stuck with redirecting to less"
- In reply to: drejcicaREMOVE_at_volja.net: "a quick malloc question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 27 Sep 2003 19:02:17 GMT
On Fri, 26 Sep 2003 22:09:06 GMT
drejcicaREMOVE@volja.net wrote:
> Hello,
> if I use a variable multiple times within my program, is it better to
> declare it as a pointer and malloc() it every time (if the value of
> the variable is changed many times)? If it's not a pointer, does it
> lead to a memory leak? However, if it is a pointer, I can use one and
> the same address every time I change its value.
1. A memory leak is usually caused by the failure of the PROGRAMMER from
calling free(3) before reusing the pointer.
The answer to your question depends on what the variable is. There is a
significant cost associated with malloc(3). Malloc(3) must first go to
the OS and request a block of memory. This is usually done the first
time before you call it, but may also be done on subsequent calls. But,
when it does not need to call the OS, it needs to search the free list
for a block that can fill your need. Additionally, a malloc block itself
has some overhead, which is usually at least one pointer and at least
one size_t. There might also be some additional information used by the
allocator. Dynamic memory allocation is a very powerful feature of both
the C language, Unix, and other operating systems, but it should never
be used lightly.
-- Jerry Feldman <gaf-nospam-at-blu.org> Boston Linux and Unix user group http://www.blu.org PGP key id:C5061EA9 PGP Key fingerprint:053C 73EC 3AC1 5C44 3E14 9245 FB00 3ED5 C506 1EA9
- Previous message: Paul Pluzhnikov: "Re: Got stuck with redirecting to less"
- In reply to: drejcicaREMOVE_at_volja.net: "a quick malloc question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|