Malloc and automatic variables

David Brown david@westcontrol.com
Fri Aug 24 09:40:00 GMT 2012


On 23/08/2012 20:02, Ian Lance Taylor wrote:
> On Thu, Aug 23, 2012 at 3:39 AM, Marcin S <msporysz06@gmail.com> wrote:
>>
>> I want to use malloc in embedded environment, where there is no memory
>> management at all - I know it sounds like a bad idea but this malloc
>> will be called only once somewhere at program start and it wont be
>> released ever, so memory fragmentation shouldn't be a problem. Unless
>> there is something i don't know.
>>
>> Let's assume I have this function
>>
>> int* vector = 0;
>> void init(int cnt)
>> {
>>     int something = 100;
>>     vector = malloc(sizeof(int) * cnt);
>> }
>>
>> So when above function is called it allocate automatic variable
>> "something", then allocates memory for vector - after work is done
>> "something" is freed.
>> Question is, will I end up with gaping hole in memory between:
>> (A) memory allocated before this function is called
>> and
>> (B) memory allocated by function for vector
>>
>> ###MEMORY_USED_BEFORE###(int sized hole)###MEMORY_FOR_VECTOR###
>>
>> Or maybe automatic variables are created somewhere else (stack?) and
>> memory wont be fragmented.
>> In case it would be significant I'll add that target environment is
>> ARM Cortex 3.
>
> Automatic variables are created on the stack.  malloc returns memory
> allocated from the heap.  The two memory areas are normally disjoint,
> so the presence of an automatic variable will not cause fragmentation
> in the heap.  Only you can say whether you have an extremely unusual
> environment in which they are the same.
>
> Ian
>

There are no fixed rules, but the most common setup (in embedded systems 
at least) is to have your data and bss segments first in memory, then 
the heap growing upwards into free space, and the stack at the top of 
ram growing downwards into the same free space.

Building an allocate-only malloc() is quite simple:

static void* topOfHeap = ???;		// Must be initialised somewhere
void * malloc (size_t size) {
	void * p = topOfHeap;
	topOfHeap += size;
	return p
}

void free (void * ptr) {
}

With this setup and memory arrangement, you only get collisions if you 
use too much total memory.  It is always possible to put some checks in 
malloc() to see if the stack is encroaching on the heap, but almost 
certainly that will not help in typical use-cases of such almost static 
systems - most of the malloc() allocations are done at startup and 
initialisation, rather than deep in the working code where the stack 
will be bigger.




More information about the Gcc-help mailing list