473,608 Members | 2,264 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory management and allocation

Hi!

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
expect.
One of my questions is then: Is it strictly necessary to allocate
memory as in:
BYTE *frame = (BYTE*)malloc(s izeof(BYTE * FRAMELEN); and later to free
this and set the pointer to NULL ? Or can I just allocate the variable
by
BYTE frame[FRAMELEN]; and assume the memory is freed on a function
return?

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(s izeof(BYTE * FRAMELEN);
...assign some values to frame...

and then call
free(frame);
frame = NULL;

why do I sometimes get a segmentation fault?

Hope someone has got some good answers for me.

Thanks

Dan Nilsen
Nov 14 '05 #1
7 1850
"Dan Nilsen" <da********@gma il.com> wrote in message
news:50******** *************** ***@posting.goo gle.com...
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
expect.
One of my questions is then: Is it strictly necessary to allocate
memory as in:
BYTE *frame = (BYTE*)malloc(s izeof(BYTE * FRAMELEN); and later to free
this and set the pointer to NULL ? Or can I just allocate the variable
by
BYTE frame[FRAMELEN]; and assume the memory is freed on a function
return?
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(s izeof(BYTE * FRAMELEN);
..assign some values to frame...

and then call
free(frame);
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
times),
- 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).

Alex
Nov 14 '05 #2
Dan Nilsen wrote:
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.
I'll assume it's still a hosted implementation.
In my program(s), I do have several functions and files as one would
expect.
One of my questions is then: Is it strictly necessary to allocate
memory as in:
BYTE *frame = (BYTE*)malloc(s izeof(BYTE * FRAMELEN);
and later to free
this and set the pointer to NULL ? Or can I just allocate the variable
by
BYTE frame[FRAMELEN]; and assume the memory is freed on a function
return?
1. You don't have to set the pointer to NULL.
2. If you need the memory only inside of the function and you know the size
in advance, there is really no need for dynamic allocation (unless FRAMELEN
is a really big value). Just define an array, which indeed does not require
a call to free().
And as a final question:
If i have code like this:
BYTE *frame = (BYTE*)malloc(s izeof(BYTE * FRAMELEN);
You don't need the cast, by the way. The type of malloc()'s return value is
pointer to void, which is compatible to any other pointer type.
..assign some values to frame...

and then call
free(frame);
frame = NULL;

why do I sometimes get a segmentation fault?


The way you write it here, there shouldn't be a problem. Perhaps you call
free() several times on the same memory?
Christian
Nov 14 '05 #3
Dan Nilsen wrote:
Hi!

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
expect.
One of my questions is then: Is it strictly necessary to allocate
memory as in:
BYTE *frame = (BYTE*)malloc(s izeof(BYTE * FRAMELEN); and later to free
Better use
BYTE *frame = malloc(sizeof *frame * FRAMELEN);
if you dynamically allocate memory. The cast of malloc()'s return
value is unnecessary in C and can hide errors; using sizeof *frame
helps avoid errors if you ever change the type frame points to
(and forget to adjust the sizeof(type) part).
this and set the pointer to NULL ? Or can I just allocate the variable
by
BYTE frame[FRAMELEN]; and assume the memory is freed on a function
return?
It depends.
If you want to use "frame" only within one function (or pass it
to other functions from that function) and do not need it after
reaching the end of the function any more (like in the form of
pointers stored somewhere else which will be used to access the
memory later on), start out with the array version.
<OT>
It is possible that you run into your limits with many large
automatic array objects. ulimit or whatever your system offers
may help you determine and if necessary adjust these limits
beforehand (automatic variables usually come from the stack,
dynamically allocated storage usually from the heap).
</OT>
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(s izeof(BYTE * FRAMELEN);
..assign some values to frame...

and then call
free(frame);
frame = NULL;

why do I sometimes get a segmentation fault?
1) The final NULLing is not necessary but may help you keep track
of invalid pointers.
2) _always_ segfaults at free() can mean many things:
- you passed a pointer to storage already free()d
- the free() call _before_ the current one got passed an invalid
argument and internals of the memory management got f...ed up
- Something else happened

Errors I helped find usually fell to equal parts in these
categories but this depends on your programming style and your
implementation.
3) _sometimes_ segfaults are uglier business.

If nothing else helps: Throw out all the code
between malloc() and free(), (replace the necessary stuff by
dummy code,) put it back in little quantities (line by line,
block by block, ...) and see when it crashes.
If you can, use a debugger and tools like valgrind.

It is probably to late for that:

Clear definition of interfaces beforehand, tests for these
interfaces written best ahead of the actual functions,
paranoid assertions in the functions as you go (within some
#ifdef PARANOIA -- #endif preprocessing directives).
Hope someone has got some good answers for me.


Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #4
Christian Kandeler wrote:
Dan Nilsen wrote:


<snip>


The way you write it here, there shouldn't be a problem. Perhaps you call
free() several times on the same memory?
Christian


I think he (or something) has changed ``frame" to point to some other
location. If that's true, he would have to restore it to point to the
original location. Otherwise, I don't see a problem with free(frame).

Regards,
Jonathan.

--
Email: "jonathan [period] burd [commercial-at] gmail [period] com" sans-WSP

"We must do something. This is something. Therefore, we must do this."
- Keith Thompson
Nov 14 '05 #5
On 02/03/05 07:40, Dan Nilsen wrote:
I'm pretty sure dynamic memory allocation is quite critical in my main
program(the server), in order to avoid any memory leakages.


I found very useful to run a lint program that warns you of mishandled
malloc/free. You still have to check all warnings but detects a lot of
possible leakages.

Ciao
Giovanni
--
A computer is like an air conditioner,
it stops working when you open Windows.
Registered Linux user #337974 <http://counter.li.org/>

Nov 14 '05 #6
Thanks guys!

All help and answers came in handy, and I have sorted out most of my
problems regarding this project. I've basically taken over this
project from someone else, and there is next to no design documents
nor comments in the code I "inherited" . This didn't make it any easier
for me - I do however have a better understanding of pointers and
memory in C, and the common pitfalls associated with the use of them.

Dan Nilsen
Nov 14 '05 #7

Hello,

just one random thougth - which it seems no one else has touched
upon. I like this style:
If the function in question is called many times (from the same scope)
, it might be a viable option to allocate the frame buffer in the
calling scope:

void function(...., BYTE *frame) {
/* Work with frame */
}

calling scope:

BYTE *frame = malloc()
/*
Code with several calls like this:
*/
function(..., frame);
/*
Finally - no more calls to function().
*/
free(frame);
Of course, this only has merit if the function using frame is called
*many times*.
Anyway - good luck;
HTH - Joakim

--
Joakim Hove
hove AT ift uib no
Tlf: +47 (55 5)8 27 90
Fax: +47 (55 5)8 94 40
http://www.ift.uib.no/~hove/
Nov 14 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
6665
by: Tron Thomas | last post by:
Given the following information about memory management in C++: ----- The c-runtime dynamic memory manager (and most other commercial memory managers) has issues with fragmentation similar to a hard drive file system. Over time, the more often use call new/delete or alloc/free, there will be gaps and fragments in the heap. This can lead to inefficient use of available memory, as well as cache-hit inefficiencies.
4
2583
by: Franklin Lee | last post by:
Hi All, I use new to allocate some memory,even I doesn't use delete to release them. When my Application exit, OS will release them. Am I right? If I'm right, how about Thread especally on Solaries OS? This means that I use new to allocate memory in one Thread and doesn't use delete to release them.
17
3842
by: ~Gee | last post by:
Hi Folks! Please see the program below: 1 #include<iostream> 2 #include<list> 3 #include <unistd.h> 4 using namespace std; 5 int main() 6 { 7 {
9
2341
by: Mike P | last post by:
I know everything about reference counting and making sure you don't have large objects lying around. I have also profiled my app with multiple tools. I know about the fact GC collects memory but not necessary give it back to the OS. It seems that .NET win app will only return memory to the OS when the OS is asking for it. But!!! When the OS is asking for it is usually too late, tons of swapping and slow performance.
72
3575
by: ravi | last post by:
I have a situation where i want to free the memory pointed by a pointer, only if it is not freed already. Is there a way to know whether the memory is freed or not?
29
4381
by: keredil | last post by:
Hi, Will the memory allocated by malloc get released when program exits? I guess it will since when the program exits, the OS will free all the memory (global, stack, heap) used by this process. Is it correct?
0
1930
by: erez_acount | last post by:
***************************************************************************** Call For Papers The 2006 International Symposium on Memory Management (ISMM'06) Co-located with PLDI 2006 Ottawa, Canada June 10-11 2006
24
19063
by: Ken | last post by:
In C programming, I want to know in what situations we should use static memory allocation instead of dynamic memory allocation. My understanding is that static memory allocation like using array is faster than malloc, but dynamic memory allocation is more flexible. Please comment... thanks.
34
2560
by: jacob navia | last post by:
Suppose that you have a module that always allocates memory without ever releasing it because the guy that wrote it was lazy, as lazy as me. Now, you want to reuse it in a loop. What do you do? Contrary to some people that will start crying to that &@@""#~ programmer that wrote this sh!!!! you keep your cool and you do the following:
0
8063
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
8148
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8338
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6816
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5475
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4024
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1594
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1329
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.