Is it possible to change the allocation area of automatic variables in C/C++?
c, c++, local-variables, memory-management, stack
Solution
It is not possible, automatic variables are stack based. But you can do whatever you want inside the constructor. So your Matrix44 will be just a thin wrapper around, say, Matrix44Impl which will point to your "custom" memory.
Problem
This is a theoretical question for both C and C++. I have a 4x4 matrix type which is defined quite simply as: ``` typedef float Matrix44[16]; ``` I also have many methods which take a `Matrix44` as a parameter, for example: ``` bool matrixIsIdentity(Matrix44 m); ``` I also have a custom memory allocation scheme in place whereby a large area of memory is pre-allocated on the heap and then I manage allocations on that prefetched memory manually. As such I have replaced/overloaded `malloc`/`new` with my own implementations. The problem is, both custom `malloc` and `new`, by nature, return a pointer, not an object. Ordinarily, I would simply do the following: ``` // Method 1 1] Matrix44 mat = { ... }; 2] bool res = matrixIsIdentity(mat); ``` However, line 1 allocated `mat` on the stack, not in my custom memory area as I would wish. An alternative is: ``` // Method 2 1] Matrix44 *mmat = myMalloc(...); 1a] Matrix44 *nmat = new ... 2] bool res = matrixIsIdentity(*mat); ``` The issue here is that I would have to litter my code with dereference operators. Now one option would be to rewrite all the methods to take `Matrix44*` instead, but, as this is theoretical, I would like to assume that is not an option. Therefore my question becomes: Is there a way to declare an automatic variable in C and/or C++ as in `Method 1 Line 1`, but have it follow an alternate allocation scheme (as in `Method 2 Line 1`)? (I appreciate this may involve compiler-related discussion but I have not added tags to that effect)