Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
8 years, 1 month ago.
How to print Free RAM, available RAM or used RAM
When using the FRDM-K64F how would you write mbed code to display or print out the free RAM or available RAM or how much RAM the program is using?
There is this question: https://developer.mbed.org/forum/mbed/topic/433/?page=2
or https://developer.mbed.org/forum/helloworld/topic/3040/
or http://developer.mbed.org/questions/7103/How-to-determine-available-RAM-at-runtim/
unsigned long heapSize() { char stackVariable; void *heap; unsigned long result; heap = malloc(4); result = &stackVariable - heap; free(heap); return result; }
.
or https://developer.mbed.org/questions/3223/How-can-I-check-for-available-RAM/
and this code for "Demonstrating crash on memory allocation" http://developer.mbed.org/users/Kemp/code/memory_test/file/883b8bc1f54a/main.cpp
Question relating to:

2 Answers
8 years, 1 month ago.
Hi Ed,
I have found a little program to know how much RAM is available for dynamic allocation.
I call FreeMem() at several critical places to understand what happens with the memory allocation.
The code is short, I hope this can help you.
Robert
/* Using malloc() to determine free memory.*/ #include <stdio.h> #include <stdlib.h> #define FREEMEM_CELL 100 struct elem { /* Definition of a structure that is FREEMEM_CELL bytes in size.) */ struct elem *next; char dummy[FREEMEM_CELL-2]; }; int FreeMem(void) { int counter; struct elem *head, *current, *nextone; current = head = (struct elem*) malloc(sizeof(struct elem)); if (head == NULL) return 0; /*No memory available.*/ counter = 0; // __disable_irq(); do { counter++; current->next = (struct elem*) malloc(sizeof(struct elem)); current = current->next; } while (current != NULL); /* Now counter holds the number of type elem structures we were able to allocate. We must free them all before returning. */ current = head; do { nextone = current->next; free(current); current = nextone; } while (nextone != NULL); // __enable_irq(); return counter*FREEMEM_CELL; }
.
posted by -deleted- 12 Apr 2015