This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Using malloc on MSP430 How to

Other Parts Discussed in Thread: MSP430G2231

Hi,

i´ve got a problem using malloc on the MSP430G2231.

Despite including the stdlib.h the debugger says there`s no source available for malloc();

unsigned short *buffer; 

buffer=(unsigned short *)malloc(512);

Though when I try to do this, it doesn´t work.

Why could that be ?? Could anybody imagine ??

  • Hi MaxE,

    the MSP430G2231 has only 128 bytes of RAM, therefore it is not possible to do malloc with such big size (512).

    You need also to set the heap memory size where the memory will be taken from when using malloc(). This is usually compiler specific, for example the following if you use CCS:

  • Ok so there´s no chance of allocating a 512 bytes buffer on this device ??

  • malloc() simply allocates existing memory; it does not - and cannot - create memory out of thin air!

    In general, dynamic allocation - and, hence, malloc() - is best avoided on small microcontroller embedded systems;  that's why it often is not included by default.

    If you do have some specific reason that really requires dynamic allocation, you should probably write your own malloc() specifically tailored to your particular requirements & constraints - another argument against a default malloc() !

  • Hello,

    like lhend mentioned before : No, it is not possible to dynamically allocate 512 Bytes of RAM on the heap of a device that has only 128Bytes of RAM.

    It also makes no sense to use dynamic heap allocation on a device with 128 bytes of RAM with 1,2,3 malloc size, as the heap fragmentation eats up all of your RAM.

    RAM in C is shared between 3 kinds of memory types: static memory like global variables that are fixed before run time, stack growing from uppest RAM address torwards lowest RAM address and heap growing from above the static alocated ram torwrds stack. For all you will need 128 bytes in your case.

    If you wish to allocate RAM anyway dynamically, then I can recommend memory pools, one memory pool implementation for example is included in contiki os (MEMB).

    memb.h :http://dak664.github.com/contiki-doxygen/a00208_source.html

    memb.c: http://dak664.github.com/contiki-doxygen/a00207_source.html

    This reduces the unknown heap size during runtime to 0, as memory pools operate with static allocated memory before runtime. If you do not have enough memory to allocate memory in this case, you will know it during binary linkage. The only unknown is the runtime stack in this case.

    Regards 

    Marco

**Attention** This is a public forum