In my project I need three arrays to store data inside.
I define a maximal number of elements as a macro variable. However, at a certain point in the setup function, the program could determine, that the arrays would actually store a smaller number of elements. In other words, it is possible (and even likely) that there is more memory reserved for the arrays than actually necessary.
As I think that memory might be a critical factor on a micro controller like the Arduino, I would like to set the excess memory free.
Is there a way to dynamically resize and shrink the arrays at runtime?
Something like this (pseudocode)
#define maxSize 50
int theArray[maxSize];
int actualSize = getActualArraySize();
// sets actualSize to a value <= 50, let's assume actualSize = 20
shrinkArray(theArray, actualSize);
// shrinkArray doesn't exist :) I need something like that.
1 Answer 1
This is a common question when designing software. The simple answer (rule of thumb) is statically allocate the maximum size of the array. In this case the maximum size of the arrays. This simple rule will keep you out of trouble and make testing etc much simpler.
Using dynamic allocation (adjusting array size etc) especially for small scale embedded systems such as the Arduino opens a "can of worms" with possible memory (heap) fragmentation and hidden concurrency and performance issues.
If the required maximum size of the array is 32 elements the application has to allow that and there is no memory to save. Statically allocating will make the sketch simpler and easier to test.
Cheers!
-
1To elaborate a little, while you CAN allocate the arrays smaller, there's really no point leaving some memory free: the program has to work even in the worst case, with the arrays as big as they'll ever be, and it won't work any better if you sometimes have some memory left over.Mark Smith– Mark Smith2016年11月15日 15:24:11 +00:00Commented Nov 15, 2016 at 15:24
theArray
as a pointer instead of array:int *theArray;
and then later allocate the required amount of memory:theArray = malloc(requredArrayLength * sizeof(int));
- Would that solve your problem?