Memory fragmentation

I’ve read that it is good practice to define variables locally rather than globally to save memory.

However, if you have a function which is called regularly, do you run the risk of fragmenting the memory by continuously creating and destroying variables?

I don’t know enough about how memory is managed to assess this, but if you define a variable globally rather than locally, will this mean that a set part of memory is then reserved for the variable and that part of memory will just continuously be overwritten rather than potentially chopping up bits of memory?

The only time I've seen that happen is with the String class, which on Arduino has poor memory management.

With normal, everyday C/C++ functions that use local variables, Arduinos can run for years, 24/7 without failure due to memory allocation problems.

There is always the possibility of a glitch due to noise in the power supply, cosmic rays, etc.

Thanks for that.
You need to watch those cosmic rays.

There's a certain amount of memory in a microcontroller, as long as you don't use all of it there's little point in worrying about wasting it. If you don't waste it with unnecessary variables it's still wasted by not being used.

The memory for local variables is created on the stack and goes away once the function returns. That's not a worry as long as you don't have so many locals in one function or get so deep into nested calls that you fill the memory up with the stack.

What you worry about fragmentation with is the heap. As long as you aren't using dynamic allocation like new or some library like String that uses it then you have no worries

1 Like

I have been using the evil Strings. I know from what i have read that they are a bad option, but you have to use what you understand at the time. I was using Strings for concatenation.

I've just discovered strcpy and strcat and i think that these will be a better option.

Thanks for the help.

1 Like

Much better, but is still possible to make mistakes, like writing past the end of the allocated character array. It helps to use the "n" variants like strncpy, strncat, etc.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.