I'm writing a program for arduino that needs dynamic memory allocation frequently, but as I don't want the memory to get fragmented, I'm also writing a "memory handler" for it. This memory handler would need to do calculations involving both pointers and size_t
variables, like this (example code is not part of program, but the structure of the calculations is the same):
size_t freeMemSize = nextPointer - currentPointer - currentSize;
Which would calculate the size of free memory between two reserved spaces.
Of course, arduino doesn't want to swallow this code, as it compares incompatible types. My questions are:
- Is a cast to the correct integer type enough to solve the problem?
- If it is, what is the "normal integer" counterpart of a pointer?
I guess this varies from processor to processor, so I should look for something like size_t, but for memory indices instead of sizes.
Board: Uno, Nano
IDE version: 1.8.2
1 Answer 1
Assume the following declarations:
uint8_t* nextPointer;
uint8_t* currentPointer;
size_t currentSize;
Then the expression is valid:
size_t freeMemSize = nextPointer - currentPointer - currentSize;
If any of the pointers are void*
the compiler cannot calculate the expression (pointer or size).
Cheers!
-
Yes, that will be it. One of my pointers were
void*
type. Thanks.sisisisi– sisisisi2017年09月23日 15:37:53 +00:00Commented Sep 23, 2017 at 15:37 -
Beware this mixing of pointers and size_t only makes sense for pointers to objects of size 1.Chris Stratton– Chris Stratton2017年09月23日 17:04:45 +00:00Commented Sep 23, 2017 at 17:04
-
@ChrisStratton The code is REALLY alpha version, and needs a lot of work, including variable types. But thanks for the warning, each advice helps to understand programming arduino a bit more.sisisisi– sisisisi2017年09月24日 17:43:35 +00:00Commented Sep 24, 2017 at 17:43
Explore related questions
See similar questions with these tags.
intptr_t
is specified to be an integer type capable of holding a pointer.