Skip to content

malloc() fails when allocating ESP.getMaxFreeBlockSize() bytes #7322

Closed
@dplasa

Description

@dplasa

Basic Infos

  • This issue complies with the issue POLICY doc.
  • I have read the documentation at readthedocs and the issue is not addressed there.
  • I have tested that the issue is present in current master branch (aka latest git).
  • I have searched the issue tracker for a similar issue.
  • If there is a stack dump, I have decoded it.
  • I have filled out all fields below.

Platform

  • Hardware: [ESP-12]
  • Core Version: [2.7.1=20701000]
  • Development Env: [Arduino IDE]
  • Operating System: [Ubuntu]

Settings in IDE

  • Module: [Wemos D1 mini r2]
  • Flash Mode: [qio|dio|other]
  • Flash Size: [4MB]
  • lwip Variant: [v2 Lower Memory]
  • CPU Frequency: [80Mhz]
  • Upload Using: [SERIAL]
  • Upload Speed: [115200] (serial upload only)

Problem Description

malloc() returns a nullpointer when allocation more than ESP.getMaxFreeBlockSize() - 16 Bytes, whereas the documentation says "ESP.getMaxFreeBlockSize() returns the maximum allocatable ram block regarding heap fragmentation".
Either the documentation should be updated or ESP.getMaxFreeBlockSize() should return a lesser size.

MCVE Sketch

#include <ESP8266WiFi.h>

void setup() {
  Serial.begin(74880);
  WiFi.mode(WIFI_OFF);

  uint16_t maxBlock = ESP.getMaxFreeBlockSize();
  uint32_t freeHeap = ESP.getFreeHeap();

  Serial.printf("free: %5ld - max: %5d\n", freeHeap, maxBlock);

  void* p = NULL;
  while (p == NULL)
  {
    p = malloc(maxBlock);
    Serial.printf("malloc(%u) = %p\n", maxBlock, p);
    --maxBlock;
  }
}
void loop() {}

Debug Messages

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 3456, room 16 
tail 0
chksum 0x84
csum 0x84
va5432625
~ld

SDK:2.2.2-dev(38a443e)/Core:2.7.1=20701000/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
free: 53840 - max: 53832
malloc(53832) = 0
malloc(53831) = 0
malloc(53830) = 0
malloc(53829) = 0
malloc(53828) = 0
malloc(53827) = 0
malloc(53826) = 0
malloc(53825) = 0
malloc(53824) = 0
malloc(53823) = 0
malloc(53822) = 0
malloc(53821) = 0
malloc(53820) = 0
malloc(53819) = 0
malloc(53818) = 0
malloc(53817) = 0
malloc(53816) = 0x3ffeedbc

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions