Some Pointers For Memory Allocation

This may be an article you’ll want to file away with a “Do Not Try This At Home” warning as we take a look into allocating memory and using Pointers from the C language. The Java and therefore Processing languages do not use pointers and you may actually find claims that pointers are error prone. It’s not that pointers are inherently problematic but programmers get careless in their use and create hard to find bugs in their programs. Since Arduino is based on the C language we have many of the C features to play with.

The Array Declarations – Processing vs Arduino article left off with a pointer declaration for ptrArray.  This article picks up from there by allocating a pointer to an array of integers.

Create a new Arduino sketch named Malloc:


#include < ctype.h >

int *ptrArray;
char *cmdString = {"Type - a, b, c or d to blink led"};
char *strFormat = {"command %c blinks %d times\n"};
char strMessage[40];
int delayTime;

void setup()
{
  Serial.begin(9600);
  ptrArray = (int *)malloc(sizeof(int)* 3);
  ptrArray[0] = 2;
  ptrArray[1] = 4;
  ptrArray[2] = 6;
  realloc(ptrArray,(sizeof(int)* 4));
  ptrArray[3] = 8;
  Serial.println(cmdString);
  delayTime = 200;
}

void loop()
{
  if(Serial.available())
  {
    int arrayPos;
    char command = tolower(Serial.read());
    arrayPos = command - 'a';

    switch(command) {
      case 'a':
        blinkLED(ptrArray[arrayPos]);
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
        Serial.println(strMessage);
        Serial.println(cmdString);
      break;
      case 'b':
        blinkLED(ptrArray[arrayPos]);
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
        Serial.println(strMessage);
        Serial.println(cmdString);
      break;
      case 'c':
        blinkLED(ptrArray[arrayPos]);
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
        Serial.println(strMessage);
        Serial.println(cmdString);
      break;
      case 'd':
        blinkLED(ptrArray[arrayPos]);
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
        Serial.println(strMessage);
        Serial.println(cmdString);
      break;
      default:
        blinkLED(0);
    }
  }
}

void blinkLED(int nTimes)
{
  
  for (int i=0; i<nTimes; i++)
  {
    digitalWrite(13, HIGH);
    delay(delayTime);
    digitalWrite(13, LOW);
    delay(delayTime);
  }
  digitalWrite(13, LOW);
}

The pointer is declared on line 03, by placing the asterisk at the front of the variable name as in: *ptrArray

Line 03. int *ptrArray;
Line 12. ptrArray = (int *)malloc(sizeof(int)* 3);
Line 16. realloc(ptrArray,(sizeof(int)* 4));

Line 12 causes the program to allocate a block of memory where the integer array will reside using the malloc function. Because we’re creating an integer array we need to assist the malloc function by telling it the size of the data type by using the sizeof(int) function. Then multiply by by the array positions wanted, in this case 3, for the total number of bytes to allocate.

Line 16 serves no real purpose in this program other than to illustrate that variables can be dynamically reallocated using the realloc function. In this statement we provide the pointer to the array being resized, ptrArray, then the size of consecutive memory to allocate. In this case we are changing the size of the integer array from 3 to 4 integer positions.

Line 13. ptrArray[0] = 2;
Line 14. ptrArray[1] = 4;
Line 15. ptrArray[2] = 6;
Line 17. ptrArray[3] = 8;

Lines 13, 14, 15, and 17 simply assign an integer value into each of the array positions. The rest of the program uses the data values to determine how many times to blink the LED on pin 13 when you type in an a, b, c, or d character.

Line 01. #include <ctype.h>
Line 27. char command = tolower(Serial.read());
Line 28. arrayPos = command - 'a';
Line 27 introduces tolower(), one of the standard C functions for string manipulation. This function guarantees upper case or lower case characters are always returned as lower case. To use this function requires including the ctype.h header file as shown on Line 01.
Line 28 does a little arithmetic that takes an ASCII character representation passed through the serial connection and subtracts 97, the ASCII representation for ‘a’. The Arduino reference page links to an ASCII chart.
Line 33.sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);

Line 33 is making use of the C language sprintf() function. Arduino hides many of the C language functions to simplify the language more user friendly. Additional references from “The C Programming Language book“.

(c) 2009 – Vince Thompson
Advertisements

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: