Using malloc() and free() in PROS

Right now I have 2D stack array that stores information about motor speeds. I’d like to make it dynamic because I suspect that its sheer size is why our robot code crashes all the time.

Here’s some of the code:

int8_t ch, cy;
int8_t data[MOTOR_LIMIT][FILTER_CYCLE_LIMIT] = { { 0 } };    // this is it
int8_t chindex[MOTOR_LIMIT] = { [0 ... MOTOR_LIMIT - 1] = -1 };
int8_t fcycles[MOTOR_LIMIT] = { 0 };
int8_t count = 0;

The only thing stopping me from making


dynamic is that I need it as long as the robot is running. Because the code ends in an infinite loop (the one in the


function), I don’t have anywhere to free the array upon program termination.

Over the past few weeks, I’ve done quite a bit of research but haven’t found anything yet. Can someone shed some light on this please?

Fjiang - Unfortunately to answer your question I need more context. What exactly are you trying to accomplish with this 2D array?

It sounds as though it offloading the data to a PC rather then attempt to store everything in memory would be a much better option.

Hi jabibi,

The purpose of the 2D array is to allow the motors to accelerate to their target speed. Each array within the 2D array stores the speed values recently applied to a specific motor. Each time


is called on that motor, the program updates the array and sets the motor’s speed to the average of the array values. My program is basically an implementation of this.

Because the values in


are generated in real-time, loading the data from an external source is, unfortunately, not an option.

If it’s inside a function just make it a static array, you are probably exceeding the stack size for the task.

As jpearman said a static array would serve you much then a dynamic array. When iterating through the static array to store your values pay special attention to your iterator to make sure you stay within bounds. Something like this would work:

* opcontrol.c

void opcontrol(){
	int motorHistory[MOTOR_HISTORY_SIZE];
	int i = 0;

		// opcontrol code

		motorHistory* = COMMANDED_POWER;

From your application it also sounds like a slew rate control function on the power values sent to the motors would give you the same desired result.*

Well, I meant make it “static”, like this

static int motorHistory[MOTOR_HISTORY_SIZE];

or this

static int8_t data[MOTOR_LIMIT][FILTER_CYCLE_LIMIT] = { { 0 } };