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

  • If you want to do ordinary math rather than pointer math, intptr_t is specified to be an integer type capable of holding a pointer. Sep 23 '17 at 17:06
  • I think you might get more answers if you moved this to stackoverflow since it not specifically an Arduino issue, once you have the solution you could run it on any processor. Sep 25 '17 at 7:23

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).


  • Yes, that will be it. One of my pointers were void* type. Thanks.
    – sisisisi
    Sep 23 '17 at 15:37
  • Beware this mixing of pointers and size_t only makes sense for pointers to objects of size 1. Sep 23 '17 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
    Sep 24 '17 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.