Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write a C application without using the heap?

I'm experiencing what appears to be a stack/heap collision in an embedded environment (see this question for some background).

I'd like to try rewriting the code so that it doesn't allocate memory on the heap.

Can I write an application without using the heap in C? For example, how would I use the stack only if I have a need for dynamic memory allocation?

like image 683
Matthew Murdoch Avatar asked Jun 22 '09 11:06

Matthew Murdoch


People also ask

Does C use heap?

In all C and C++ code, nearly all of your data is stored in only one of two types of memory storage: All variables allocated by malloc (or new in C++) is stored in heap memory.

Why do we need heap allocation for programming?

Heap allocation is required for languages that support dynamic data structures. Dynamic data structures are data structures that grow and shrink as you need them to by allocating and deallocating memory from a place called the heap.

Does C automatically allocate memory?

3.2. 1 Memory Allocation in C Programs The space is allocated once, when your program is started (part of the exec operation), and is never freed. Automatic allocation happens when you declare an automatic variable, such as a function argument or a local variable.

Does C require a stack?

The C language requires (as chqrlie, points out) some mechanism to implement automatic storage and keep track of function call return points. In practice this is almost invariably a stack.


1 Answers

I did it once in an embedded environment where we were writing "super safe" code for biomedical machines. Malloc()s were explicitly forbidden, partly for the resources limits and for the unexpected behavior you can get from dynamic memory (look for malloc(), VxWorks/Tornado and fragmentation and you'll have a good example).

Anyway, the solution was to plan in advance the needed resources and statically allocate the "dynamic" ones in a vector contained in a separate module, having some kind of special purpose allocator give and take back pointers. This approach avoided fragmentation issues altogether and helped getting finer grained error info, if a resource was exhausted.

This may sound silly on big iron, but on embedded systems, and particularly on safety critical ones, it's better to have a very good understanding of which -time and space- resources are needed beforehand, if only for the purpose of sizing the hardware.

like image 78
Metiu Avatar answered Sep 26 '22 05:09

Metiu