Skip to main content
Tuoman
Senior II
April 22, 2020
Question

Statically allocate N number of containers?

  • April 22, 2020
  • 2 replies
  • 1096 views

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!

This topic has been closed for replies.

2 replies

Martin KJELDSEN
Principal III
April 22, 2020

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

Tuoman
TuomanAuthor
Senior II
April 24, 2020

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.

Martin KJELDSEN
Principal III
April 24, 2020

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
April 24, 2020

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

Tuoman
TuomanAuthor
Senior II
April 24, 2020

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

Martin KJELDSEN
Principal III
April 28, 2020

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