Using malloc(), realloc(), and free() on teensy 3.2

Status
Not open for further replies.

jondavid

Member
I've been working on a library to read bitmap files stored on external flash using the SerialFLash library and I've hit a roadblock that I'm pretty sure is related to the way I'm trying to implement the malloc and realloc functions, but I'm also wondering if there is anything teensy specific that I may not be taking into account.

Initial load of bitmap file and initial malloc() of array works just fine. It's when I try to free() the memory and realloc() that everything freezes. My implementation is shown in the code below.

.h
Code:
    //Pointer for location to hold pixel data
    char * image=0;
    CRGB *palette;

.cpp
Code:
void sfBMP::load(const char *filename){
  free(palette);
  free(image); 
  file.close();
  
  file = SerialFlash.open(filename);
  address = file.getFlashAddress();
  fileSize = file.size();

  image = (char*) realloc(image,fileSize); 
 
  SerialFlash.read(address,image,fileSize);
  tracker = 0;

  verify();
  
};
 
It has been a long time since I have used realloc. But I am pretty sure you don't use it on a pointer that you already freed (like image). You use it on a pointer that is currently already allocated by malloc. If you freed the pointer, you should just call malloc again.

But again could be wrong
 
No, I believe you are correct. I was originally using free() and malloc() and then read about malloc() not actually being what I should use to reallocate to a different size so I switched to realloc() and didn't think about removing the free(). However.... Same result after trying that fix as well. SO.... I added some serial print lines so I could verify exactly where everything was freezing and it turns out that it's never making it to realloc and it's actually getting stuck at SerialFlash.open(). Going to have to look into that a little more to see what I'm doing wrong there.
 
Status
Not open for further replies.
Back
Top