This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Malloc and automatic variables


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]