Out of Memory Handler

For this handler, how is the out of memory calculated? I tried searching within github, but I couldn’t find it.

System.on(out_of_memory, outOfMemoryHandler);

Is it calculated to something like this?

void fragmentationCheck() {
  static uint32_t prevFragCheckMillis = 0;
  static uint32_t prevFragPublishMillis = 0;
  static uint32_t freeMemory = 0;
  static uint32_t largestBlock = 0;
  static float fragmentationPercent = 0;
  static bool runAtStartup = true;

  if ((millis() - prevFragCheckMillis > (60000 * 60)) || runAtStartup) {
    runtime_info_t info;
    memset(&info, 0, sizeof(info));
    info.size = sizeof(info);
    HAL_Core_Runtime_Info(&info, NULL);
    largestBlock = info.largest_free_block_heap;
    freeMemory = System.freeMemory();

    fragmentationPercent = ((1 - ((static_cast<float>(largestBlock)) / freeMemory)) * 100.0);
    // Serial.print("largestBlock : ");Serial.print(largestBlock);
    // Serial.print("   freeMemory : ");Serial.print(freeMemory);
    // Serial.print("   fragmentationPercent : ");Serial.println(fragmentationPercent);

    char memoryCharArray[80];
      snprintf(memoryCharArray, sizeof(memoryCharArray),
        "%u.%u.%.2f.%u"
        , largestBlock
        , freeMemory
        , fragmentationPercent
        , Time.now()
      );
    
    if (millis() - prevFragPublishMillis > (24*60*60*1000)) { // publish every 24 hours
      #if PLATFORM_ID == PLATFORM_ELECTRON_PRODUCTION
        publishAsync("fragInfo", memoryCharArray);
      #elif PLATFORM_ID == PLATFORM_P1
        if (Particle.connected() && WiFi.ready()) {
          Particle.publish("fragInfo", memoryCharArray, 60, PRIVATE);
        }
      #endif
      prevFragPublishMillis = millis();
    }
    
    if (fragmentationPercent > 50.0) { //reset device if too fragmented
      #if PLATFORM_ID == PLATFORM_ELECTRON_PRODUCTION
        publishAsync("fragRst", memoryCharArray);
      #elif PLATFORM_ID == PLATFORM_P1
        if (Particle.connected() && WiFi.ready()) {
          Particle.publish("fragRst", memoryCharArray, 60, PRIVATE);
        }
      #endif
      delay(2000);
      System.reset();
    }

    runAtStartup = false;
    prevFragCheckMillis = millis();
  } 
}

The out of memory handler happens when a memory allocation (malloc, new, strdup, etc.) fails. This occurs whenever the largest free block if smaller than the allocation request size, regardless of how much is available in total.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.