Home > Back-end >  Arduino: PROGMEM malloc() issue causing exception
Arduino: PROGMEM malloc() issue causing exception

Time:12-25

I am trying to dynamically allocate memory for a char pointer stored in the flash memory.

I need to read a file from flash memory using LittleFS file system and copy it to a character array which also needs to be stored in the flash memory using PROGMEM. I cannot store it in the RAM because of limited space. Also I cannot hardcode the character array directly in the sketch, because I need the ability to change the file during runtime and have it persist after reboot.

If I don't use PROGMEM for the char pointer, the sketch works fine. But adding PROGMEM causes the ESP8266 to throw an exception and reboot and become an infinite loop. This is a simplified sketch showing what I'm trying to achieve.

#include "LittleFS.h"
char* arr PROGMEM;
void setup() {
  Serial.begin(115200);
  LittleFS.begin();
  
  File file = LittleFS.open("/test.txt","r");
  arr = (char*)malloc(file.size() sizeof(char));
  int len = file.size()/sizeof(char);
  for(int i = 0; i < len; i  ){
    arr[i] = file.read();
  }
  arr[len] = '\0';

  while(1){
    Serial.println(arr);
    delay(1000);
  }
}
void loop(){}

CodePudding user response:

PROGMEM is processed by the linker at build time. Linker positions the array into flash memory address space. Only constants can use the PROGMEM directive.

malloc allocates heap memory which is an address range in the dynamic RAM. It is possible to write to flash at runtime like the LittleFS library does, but that is not done with malloc.

Process the file as you read. Do it the same way you planed to process the array read from file.

  • Related