So, I am given a global pointer p. Let’s say it is of type char*, but it doesn’t really matter, that points to a piece of prereserved memory that I am managing manually.
I am also given a type T that I want to allocate memory for. I have to take care of proper memory alignment.
For the sake of simplicity let’s assume only one thread is going to execute the function, we don’t care about synchronisation, etc.
So my idea is to write something like this:
template <typename T>
T *alloc() {
int alignment=__alignof(T);
return (T*)((p+alignment-1) & ~(alignment - 1));
}
Unfortunately this won’t compile because you cannot have bitwise “and” operator on a pointer. You cannot also divide or multiply a pointer.
A solution would be to cast the pointer to int to obtain a plain address, but if I try to compile it for 64-bit code, this may crash as pointers are not 64-bit integers.
So, my problem boils down to a question, is there some macro to detect the size of a pointer, so that I could create an integer of matching size.
Alternatively, maybe there is already defined a type which always matches the size of a pointer, but accepts all arithmetic operations?
Or finally, maybe there is another, different way to accomplish my goal?