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)
C realloc() If the dynamically allocated memory is insufficient or more than required, you can change the size of previously allocated memory using the realloc() function.
3.2. 1 Memory Allocation in C Programs The space is allocated once, when your program is started (part of the exec operation), and is never freed. Automatic allocation happens when you declare an automatic variable, such as a function argument or a local variable.
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.
In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With