Re: Memory management and allocation
From: Alex Fraser (me_at_privacy.net)
Date: Thu, 3 Feb 2005 07:44:30 -0000
"Dan Nilsen" <email@example.com> wrote in message
> I'm writing a small piece of software that basically runs on an
> embedded system with a Power-PC cpu. This runs on a stripped down
> version of Linux - Busybox.
> As I'm writing a piece of code that basically acts as a server and
> that will be running for weeks or months and probably even longer,
> memory management is a topic that is quite crucial.
> Not being a very experienced C programmer, and with next to no help in
> the company I currently work in I turn to this forum.
> In my program(s), I do have several functions and files as one would
> One of my questions is then: Is it strictly necessary to allocate
> memory as in:
> BYTE *frame = (BYTE*)malloc(sizeof(BYTE * FRAMELEN); and later to free
> this and set the pointer to NULL ? Or can I just allocate the variable
> BYTE frame[FRAMELEN]; and assume the memory is freed on a function
Personally, I avoid malloc()/free() where practical in general. It is
typically practical if either the allocation size is small and constant, and
the memory is required only for the lifetime of a function, or the
allocation size is constant and required for the lifetime of the program.
The former seems to apply in your case.
Using malloc()/free() is usually slower and can result in heap
fragmentation, both of which can be quite important in embedded systems.
If using malloc()/free() in C, it is not necessary to cast the return value
of malloc() (and for reasons that are mentioned here from time to time, I
recommend not casting). Nor is it usually necessary to set the pointer to
NULL after calling free(); where it's not necessary, this is typically done
to guard against further (erroneous) use of the freed memory.
> I'm pretty sure dynamic memory allocation is quite critical in my main
> program(the server), in order to avoid any memory leakages.
> And as a final question:
> If i have code like this:
> BYTE *frame = (BYTE*)malloc(sizeof(BYTE * FRAMELEN);
> ..assign some values to frame...
> and then call
> frame = NULL;
> why do I sometimes get a segmentation fault?
Common causes of problems when using malloc() and free() are:
- forgetting to #include <stdlib.h>,
- not checking the return value of malloc(), which may be NULL to indicate
failure (problem occurs when you try to dereference the pointer),
- writing outside allocated memory, often somewhere else in the program
(problem most often occurs when calling free(), but can occur at other
- calling free() twice with the same pointer value (problem occurs on the
second call), and
- passing free() a pointer value other than one returned by malloc(),
calloc() or realloc() (including a corrupted pointer value).