Reputation: 64739
How do you minimize dynamic memory allocation in C++?
I'm writing some sketches for an Arduino Mega, and on occasion it's hanging, and I suspect it's suffering from memory fragmentation. However, I'm a little unclear as to when variables are allocated.
If I have a class with a method do_stuff
like:
class MyController{
public:
MyController(){
...init...
}
void do_stuff(){
int value = 123;
}
};
I instantiate MyController
once but then execute do_stuff()
multiple times. Does the program dynamically allocate value
each time I call the method or just once when I instantiate the class?
If the former, would it be better to change the method variable to a class variable, so it's only allocated once, and doesn't risk fragmenting the heap?
Upvotes: 1
Views: 127
Reputation: 179907
On typical platforms, and I don't believe an Arduino is different in this respect, int value
probably won't take memory. It will be in a register. (Small variable, local). If not, it will be on the CPU stack, which doesn't fragment, and it recycled whenever the function returns.
Upvotes: 2
Reputation: 1257
I can't say where MyController
will be instantiated, but each call of do_stuff
instantiates value
on the stack once. This memory will be freed as soon as do_stuff
is left and since there is no recursion, there will not be several instances of value
at once.
Upvotes: 0