Skip to main content
Graduate II
August 2, 2025
Solved

STM32L4: Does the USB device even use the heap?

  • August 2, 2025
  • 1 reply
  • 283 views

I am using the USB CDC driver code provided by ST in stm32cubeide, and am trying to figure out a proper minimum heap size. I have found various slightly conflicting answers, but the consensus seems to be that 512 bytes is not enough.

In the same application, I also use FATFS, but I'm not 100% sure if that is supposed to use the heap.

Now I wanted to test just how much of the heap is in fact overwritten. To do this, I brutally stored the byte sequence AA BB CC DD over and over in the first 1 KB of the heap. I did that with this piece of code inserted in main.c, immediately after the entry point:

uint32_t *heapPtr;
uint32_t *heapOrigin;

(...)

/**
 * @brief The application entry point.
 * @retval int
 */
int main(void)
{

 /* USER CODE BEGIN 1 */

 uint16_t i;
 heapOrigin = malloc(4);
 free(heapOrigin);
 heapPtr = heapOrigin;
 slDebug6 = (uint32_t)heapOrigin;
 for (i = 0; i < (1024 / sizeof(*heapOrigin)); i++)
 {
 *heapPtr = 0xDDCCBBAA;
 heapPtr++;
 }

 /* USER CODE END 1 */

The malloc(4) function call in line 16 is there just to give me an address to the heap, as I know of no other way to do this. The for loop fills 1 kB with the byte sequence, from the beginning of the heap.

In the application, I can request a readout of the heap memory contents. Imagine my surprise when I discovered that, even though I'm communicating via the USB port, not a single byte in the heap is overwritten. My byte sequence is intact from the first byte (at 0x20006D80), through the following 1 KB.

Readout of SRAM from address 0x20006D80:
AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD
AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD
AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD
AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD
AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD
AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD
AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD
AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD
AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD AA BB CC DD
AA BB CC DD...
And so it continues.

Can someone explain what is going on here?

Have I completely misunderstood the heap? Or does the USB device driver actually not use the heap after all?

    This topic has been closed for replies.

    1 reply

    EThom.3Author
    Graduate II
    August 2, 2025

    Awesome – thanks!