How to prevent stack overflow/optimize large structs (with internal arrays)

Dear everybody,

I have a program with the standard setup() and main()-loop, alongside that I have .h/.cpp library that I made for measuring some sensors. In my header file, I’ve made a struct as follows:

   // Measurement Struct
   typedef struct
   {
      int SenID;
      union
      {
         int intVal;
         float floatVal;
      } measurements[MAX_NUMBER_OF_PAYLOADS];
   } MeasurementPackage;

In this case, MAX_NUMBER_OF_PAYLOADS is 180. During the program execution I create 7 instances of this struct within a class function, which allocates more space that possible on the main loop stack (6144 byte limit). I understand the overflow, but I do not understand the solution (yet)

My question is how I can maintain same struct and internal types, but declare them outside the main loop stack to circumvent the stack limit and prevent the overflow?

All the best,

If you really need all of these 5068 bytes concurrently you could either declare them globally or put them onto the heap.

But I’d also (re)consider whether I’d really need to hold all that data in memory at once.

4 Likes

Thank you for the reply ScruffR, I was definitely looking for the solution in the wrong place. I started the daunting task of refactoring and solved it in combination with the PublishQueuePosix library from Rick.

Just out of curiousity, as I do not program hardware usually - how would I ‘practically’ put it on the heap or declare it globally within a library? Because it didn’t seem to have any effect when I tried the global declaration.

“Within” a library you’d rather not create global variables/objects.
However the library can hold the definition and in your main module you create global variables/objects of that type which you’d then provide to any of the “library classes”.

With regards to the heap, you’d use any of the following

But be careful about heap fragmentation!

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.