Hi everyone.
I wrote a small library for the AVR family which enables easy use of STDIN, STDOUT and STDERR (you can look at the code HERE).
Basically, it accepts a device object (such as "Serial" or "LCD", etc..) and allows using printf, getc and other functions to write or read a character device).
The library currently also has a pushStream and popStream function (not shown in the old github upload) that allows saving the current device, setting a new device, then restoring the original device (like a stack push and pop). To clarify, it would be used like this:
void debug (void)
{
STDIO.pushStream (LCD); // save current device, setup LCD
printf ("Cursor pos: %d\n", curpos); // show cursor pos on LCD
STDIO.popStream(); // restore std streams to previous
}
Currently, there is only one set of pointers in which to save the streams before setting new ones. This means that if more than one pushStream is called, only the last one is saved, the previous ones are lost.
I modified the code to provide multiple stream pointers, accessed with an index. Like this:
Before:
Print *_stream_ptr0_save; // save standard in pointer
.... // two more - for stdout and stderr
After:
Print *_stream_ptr0_save[16]; // save up to 16 stdin pointers
.... // two more - for stdout and stderr
This works, but I don't like it because saving less than 16 pointers is a waste of memory and trying to save more obviously fails.
I want to use the realloc function to dynamically create new "slots" as needed.
My questions are:
- Can I use realloc to also decrease the number of slots (i.e. when someone does a popStream() the save slots should be deallocated and the ram freed.
- When the last slot is popped and deallocated, can I consider the memory "free" (i.e. would not need to do a call to free(_pointer))?
I know that supposedly the malloc and realloc functions are (unreliable)? in avr-gcc. However, I have another function to do a readline (get typed text from a device... usually Serial) and this function uses realloc for EACH character typed. Of course, the readline buffer needs to be freed after each call, but it works reliably... have NEVER had an error or crash, so I personally trust avr-gcc memory allocation.
So, do you think that the final realloc will have the effect of freeing the pointer allocation?
Thanks!