Hello all,
Background to the question:
I have code that I'm trying to modify and there is a section where servos are initialized. The code is to control an arduino through LabView over serial communications. This is done by uploading a sketch to the arduino and then initializing stuff in LabView. My question is with the Servo initializing specifically,
servos = (VarSpeedServo*) malloc(2*sizeof(VarSpeedServo));
for(int i=0; i<2; i++)
{
servos[i] = VarSpeedServo();
}
I have been searching around a lot to figure out what malloc() does. The first site that helped was Why Use Pointers?: Dynamic Memory Allocation | SparkNotes. Here, I understood malloc() is for dynamic memory allocation and it adds things onto the heap. The reason for the heap is that when a program is running, it can create room for variables that are create at Run-time instead of Compile-time.
I also searched the forums and found Memory Usage - Programming Questions - Arduino Forum. Specifically this section.
- Instantiated global or static
- Uninstantiated global or static (aka BSS)
- Dynamically allocated
- Function local variables
When you create one of the first two kinds of variables it is placed at the bottom of the memory space - instantiated first, uninstantiated ones second. Above that goes the heap, which contains any dynamically allocated variables (memory allocated by malloc() or new()). Then there is the "free" space. Finally, at the top of memory, is the stack. In the stack goes (amongst other things) the function local variables.
Global / static variables are created at compile time and can be reported by the IDE as an amount of RAM used. The other kinds are created on the fly by the program - the IDE has no clue what they are or how big they are, or how many of them.
Question:
Is the reason that the servos are in malloc() is because the sketch is uploaded to the arduino with the servos undeclared (Compile-time) and then LabView declares them while the arduino is running?
If that's the case, I am writing code in LabView which needs two servos. I can just declare them as normal without having to do the malloc() stuff because I know the servos have to be there and I don't have to worry about them being created on the fly.
Thank you in advance,
Matt