// Using the heap for memory allocation #include "mem_syms.h" #define ADDR DEC void setup() { // a pointer to an int long int * x_p; // a pointer to a char char * y_p; // to keep track of where the heap starts and ends for us // there might already be stuff on the heap, which we want to // ignore. char * hs; char * he; char * p; Serial.begin(9600); Serial.println("MEM07"); Serial.print("Avail mem:"); Serial.println(AVAIL_MEM, DEC); Serial.print("Heap starts at:"); Serial.println((unsigned int) HEAP_START, ADDR); Serial.print("Heap ends at:"); Serial.println((unsigned int) HEAP_END, ADDR); /* allocate memory for an int from the heap and remember its address we could say: x_p = (int *) malloc(sizeof(int)); but then if we changed the type of x_p we would probably forget to fix the malloc call and things would break, subtly and horribly So instead we use the typeof and sizeof compiler operators */ Serial.print("Allocate a chunk, size:"); Serial.println(sizeof(*x_p)); hs = HEAP_END; x_p = (typeof(x_p)) malloc(sizeof(*x_p)); // why is this an inefficeint use of memory? //X y_p = (typeof(y_p)) malloc(sizeof(*y_p)); he = HEAP_END; // if x_p == 0, the null pointer value, then malloc failed Serial.print("Avail mem:"); Serial.println(AVAIL_MEM, DEC); Serial.print("Heap starts at:"); Serial.println((unsigned int) HEAP_START, ADDR); Serial.print("Heap ends at:"); Serial.println( (unsigned int) HEAP_END, ADDR); // why did we use 2 bytes from the heap more than we expect for x_p? *x_p = 0x89abcdef; Serial.print("x_p:"); Serial.println( (unsigned int) x_p, ADDR); Serial.print("*x_p:"); Serial.println( (unsigned int) *x_p, HEX); Serial.print("y_p:"); Serial.println( (unsigned int) y_p, ADDR); //Y *y_p = 'H'; Serial.print("*y_p:"); Serial.println(*y_p); // print the contents of the heap we just allocated from Serial.print("Heap:"); for ( p = hs; p < he; p++) { unsigned char c = *p; Serial.print( c, HEX ); Serial.print(" "); } Serial.println(); } void loop() { }