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.

How can I use heap functions, like malloc(), in Energia and G2553 LaunchPad?

Other Parts Discussed in Thread: MSP430G2553, ENERGIA

So the heart of my problem is that I need a dynamically sized array to hold note frequencies in a scale. The number of notes in a scale can vary (e.g. pentatonic vs major) and the number of octaves in that scale can vary (1 to 3). The worst case scenario is a Chromatic scale (12 notes) and 3 octaves for a total of 36 notes. Since each array element would be a 16-bit integer, that totals to 72 bytes. 

I would like to be able to dynamically size the "ScaleNotes" array to hold a list of note frequencies, however I cannot use heap functions like malloc(), free(), realloc() to do so. I am using the MSP430G2553 LaunchPad and Energia.

If I cannot use a dynamically sized array, is there an alternative method such as using the stack to do this?

Thanks,

EB

  • Eric Bauer said:
    If I cannot use a dynamically sized array, is there an alternative method such as using the stack to do this?

    Allocate "worst case array" and hold number of notes in separate variable. That's it! - Your application definitely does not require heap functions. Actually if you are using heap on small microcontrollers like msp430g2553, you are not doing it right.

  • So my application is using a photoresistor to determine the note to be played by a piezo buzzer. I was hoping to be able to read the analog light value, and map that to a number (0 to #ofNotes-1) that could index a note in that "ScaleNotes" array.

    I will try allocating the worst case and track the number of notes.

    Could you share why using heap on the g2553 is not correct, specifically?
  • >I will try allocating the worst case and track the number of notes.

    Yes. And create _static_ array that resides in the flash memory, such way saving precious RAM.

    >Could you share why using heap on the g2553 is not correct, specifically?

    msp430g2553 have just 512 bytes of RAM for everything - variables, stack and heap (if used). On 16 bit CPU systems each heap allocation will take at least extra 2 bytes of overhead. There's also heap fragmentation danger. Small systems usually have small tasks which usually does not require complex and dynamic data structures. To conclude: if you can avoid using heap in your tiny embedded microcontroller - do so. After all what you can do with 400 bytes of memory? - Put relational SQL database there? Further reading.

  • I was able to get it working by rearranging my other code a bit. Thank you for your help!

**Attention** This is a public forum