http://mbed.org/users/okini3939/notebook/mbed256_memory/

Dependencies:   mbed

main.cpp

Committer:
okini3939
Date:
2011-07-16
Revision:
0:84a4229a4f34

File content as of revision 0:84a4229a4f34:

#include "mbed.h"
#include <new>
#include <setjmp.h>

#define MAX 320

#undef USE_MALLOC // malloc or new

Serial pc(USBTX, USBRX);
jmp_buf jbuf;

void no_memory () {
    pc.printf("new: no memory!\r\n");
    longjmp(jbuf, 1);
//    exit(-1);
}

int main() {
    volatile int i; // volatile
    int j;
    char *dummy[MAX];

//    set_new_handler(0); // return null
    set_new_handler(no_memory); // new handler function

    if (setjmp(jbuf) == 0) {
        // allocate to memory

        for (i = 0; i < MAX; i ++) {
            pc.printf("%d, ", i);
#ifdef USE_MALLOC
            dummy[i] = (char*)malloc(100);
#else
            dummy[i] = new char[100];
#endif
            if (dummy[i] == NULL) {
                pc.printf("malloc: no memory!\r\n");
                break;
            }
        }
        
    } else {
        // return from longjmp

    }

    pc.printf("allocated %d Bytes\r\n", i * 100);

    for (j = 0; j < i; j ++) {
#ifdef USE_MALLOC
        delete [] dummy[j];
#else
        free(dummy[j]);
#endif
    }

}