I'm working on image processing and I need to use big Images in a critical system.
A good practice for critical systems is to avoid dynamic allocation of memory but what is the design/recommendations for static memory allocation?
If we do a static allocation of a big matrix we get stack overflow.
class test
{
public:
test(){};
~test(){};
private:
float m_bigMatrix[3000000];
};
To solve this problem we can define the matrix as static, but then this matrix will be the same for all the instance of this class.
static float m_bigMatrix[3000000];
The other solution is to have a static object.
static test t;
I've got a solution from another forum where it was suggested that the best approach would be to use a class specific for memory management.
All the instances of the class are static and are used by other classes throughout the code.
Here is a sloppy version for this solution (it's just an example):
class MemManager
{
public:
MemManager(){ m_counter = 0u; }
~MemManager(){ printf("Out of MemManager nbr %d\n", m_counter); }
uint16_t getCounter() { return m_counter; }
uint16_t getData(uint32_t pos) { return m_data[pos]; }
void setCounter(uint16_t val) { m_counter = val; }
void setData(uint16_t val, uint32_t pos) { m_data[pos] = val; }
private:
static const uint32_t MEM_SIZE_DATA = 100000000u;
uint16_t m_counter;
uint16_t m_data[MEM_SIZE_DATA];
protected:
};
class MemUser
{
public:
MemUser(){ m_memManager = NULL; }
~MemUser(){ printf("Out of MemUser\n"); }
void init(MemManager& memManager) { m_memManager = &memManager; };
uint16_t getCounter() { return m_memManager->getCounter(); }
uint16_t getData(uint32_t pos) { return m_memManager->getData(pos); }
void setCounter(uint16_t val) { m_memManager->setCounter(val); }
void setData(uint16_t val, uint32_t pos) { m_memManager->setData(val, pos); }
private:
MemManager *m_memManager;
protected:
};
int main()
{
static MemManager mManager;
mManager.setCounter(1);
{
MemUser mUser;
mUser.init(mManager);
printf("Exit scope\n");
}
for(uint8_t i = 1u; i<5u; i++)
{
static MemManager mManager2;
printf("Note that mManager2 is the same: %d\n", mManager2.getCounter());
mManager2.setCounter(i);
}
printf("Exit process\n");
return 0;
}
So, is this correct? What is the best solution?