cancel
Showing results for 
Search instead for 
Did you mean: 

Statically allocate N number of containers?

Tuoman
Senior II

Hello,

I want the user to be able to configure UI. There is configuration view (settings menu) which will add N number of containers to another view.

Currently there is no customization, only fixed number of containers are allocated.

parameterContainer parameterContainer1;
parameterContainer parameterContainer2;
parameterContainer parameterContainer3;
parameterContainer parameterContainer4;

I want that user can setup N number of these to the view (up to 10 containers). I will also have 4 types of parameterContainerA, parameterContainerB etc. to select from, so I cannot allocate 10 of all of these.

How can I achieve such functionality?

I know I could use malloc like this:

addContainer(Type type)
{
malloc(container);
}

But can I do such feature by allocating statically?

Thanks!

7 REPLIES 7
Martin KJELDSEN
Chief III

Since you know there'll be a worst case scenario of 10 containers, jut allocate them up front.

parameterContainer containers[NR_OF_CONTAINERS];

Add them all to the root container. Based on the user configuration you keep track of their state, displaying or hiding them, and whatever else.

/Martin

Hmm, okay, C++ does not have any way to create object that allocates given amount of objects?

E.g.

Home1View(

1 /*number of A containers*/

4 /*number of B containers*/,

2 /*number of C containers*/,

3 /*number of D containers*/)

Otherwise I must allocate MAX_NUM (10 presumably) of each, taking +80kB of RAM.

You also have to consider your RTOS memrory alliocation scheme here. By default we use static allocation in TouchGFX, also for RTOS in our Application Templates. Bjarne Stroustrup once said "After liftoff, never use new". FreeRTOS, for instance, has dynamic memory allocation schemes you can use if you want to dynamically allocate .

/Martin

chaaalyy
Senior II

Hmmmm....

maybe declaration as pointer and instantiate dynamically later ?

parameterContainer* parameterContainer1 = nullptr;

and later on:

parameterContainer1 = new container....

So you would "waste" just the space for the pointers on stack (anyway the memory is reserved somewhere in heap, instead of stack... To refine this, you can point them to external sdram maybe)

You also could work with vector that way

I would also like to keep with static allocation to prevent memory leaks, dangling pointers etc.

But I guess there is no way around this, configurable memory is always the maximum allocation... Otherwise must allocate dynamically.

Problem here is that there is 4 types of containers, which all will never be used simultaneously, only 10 max total out of 40 options...

Yes, this would be the malloc solution proposed. I use FreeRTOS, so I would probably need to use pvPortMalloc instead of new.

Be sure to use the correct heap implementation to make malloc thread safe.