Write error "No memory" to a file without memory?

I would like to register and possibly warn the user that the program should be out of memory, which allows them to try to free some (I hope). Although I can pre-select the necessary GUI objects needed to display the situation, my concern is that in this situation more basic operations using cstdio , such as opening or writing to a file, may not be possible.

My question is , if the program can no longer dynamically allocate memory at all, is it possible to use cstdio ? Are there any special measures that I need, for example, if the file is previously open or not use the buffer? Will the cstring functions function? Any other possible hurdles to know about this type of scenario?

(Warning that the user is a luxury in this case, the main task is to write the error to the file, then try to save the corresponding data using cstdio, and then warn the user in this order)

+6
source share
1 answer

A short answer to your “maybe not” question (see this answer: fooobar.com/questions/302908 / ... ). There are open source versions of snprintf () that do not use dynamic allocations. I would use this and mmap (2) to write to your file.

I guess the reason you want to use cstdio, you already have some fancy registration / serialization code that uses cstdio. Given this, I will now keep this decision at a high level.

In this case, I would first allocate a buffer large enough to hold your error message and recovery data (a la @ Retired-Ninja). I would make a buffer of at least one page size (4096 bytes in my Linux package). I also opened the log file I want to write to, and mmap (2) this file with the buffer size that I need.

In my memory exception handler, I first freed a buffer (to give me some memory to work with) and built an error message in the mmap'd file using the free version of snprintf without malloc. I would then fsync the file (I did not trace the fsync source code to check how much or how much memory it allocates, but it should be less than cstdio). Then I close the file, do whatever I want (GUI processing, etc.), and exit.

When my program exits normally, I simply delete the log file that I created using mmap.

If the amount of data you are trying to save is large (for example, larger than a page) and variable, you can simply allocate a buffer on one page and create a log file one page at a time. Or you can do something like fooobar.com/questions/767944 / ....

NTN.

- Jason

+1
source

All Articles