c++memory-managementnew-operatormisrastatic-memory-allocation

C++ memory management and Misra


I need some clarification about c++ memory management and MISRA guidelines..

I have to implement one program that it's MISRA compatible so I have to respect a important rule: is not possible to use 'new' operator (dynamic memory heap).

In this case, for any custom object, I must use static allocation:

For example:

I have my class Student with a constructor Student(int age). Whenever I have to instantiate a Student object I must do it this way:

int theAge = 18;
Student exampleOfStudent(theAge);

This creates an Student object exampleOfStudent. In this way I do not to have to worry about I do not use destructors. Is this correct all this? Are there other ways to use static memory management? Can I use in the same way std::vector or other data structure? Can I add, for example, a Student instance (that I created as Student exampleOfStudent(theAge)) into a std::vector.


Solution

  • Student exampleOfStudent(theAge); is an automatic variable, not static.

    As far as I remember, MISRA rules disallow all forms of dynamic memory. This includes both malloc and new and std::vector (with the default allocator).

    You are left with only automatic variables and static variables.

    If your system has a limited amount of RAM you don't want to use dynamic memory because of the risk you will ask for more memory than is available. Heap fragmentation is also an issue. This prevents you from writing provably correct code. If you use variables with automatic or static storage a static analysis application can, for instance, output the maximum amount of memory your application will use. This number you can check against your system RAM.