Freeing memory of memfile

I'm loading binary data stored in an array into allegro using al_open_memfile(). The docs of allegro states:


It should be closed with al_fclose. After the file is closed, you are responsible for freeing the memory (if needed).

How exactly can I do this?

Thanks for the help

Trent Gamblin

If the memory you pass to al_open_memfile is dynamically allocated, you have to free it with free (C) or delete[] (C++).

char *buffer = new char[1000];
delete[] buffer;

If it's not dynamically allocated, like:

static char buffer[1000] = { ... };

Then you shouldn't free it.


Thanks, that's what I needed


You can use a function like file_size_ex() (or whatever's equivalent for Allegro 5) to determine how large your buffer needs to be, if you want to avoid hard-coding file sizes in your program.

raynebc said:

determine how large your buffer needs to be

This is about memfiles, which is when you open a block of memory as a file, not reading files on disk into memory.

Trent Gamblin

They can be related. I think it was the TGA loader... it reads a byte/word at a time from file and is really slow. Much faster if you load the file into memory and load it with the memfile addon.


it reads a byte/word at a time from file

This shouldn't be a problem in itself, because the actual I/O is typically buffered, see setbuf(). Now maybe it involves back-and-forth seeking.

Trent Gamblin

Try it yourself. I already have.

Thread #612772. Printed from