I would like to have a variable to persist even after program termination. In other words, I'd like for a variable to remain in the memory even after an application exits from the main function. So, if my application is launched again, it could access that variable directly from the memory. Is this even possible? Would dynamic allocation, e.g. array=new int[size]
, do the trick?

- 5,898
- 9
- 44
- 81
-
What platform/OS? It's not possible in standard C++, but a lot of platforms offer something akin to this. – Flexo Jul 27 '12 at 14:04
-
Windows 7. what platforms allow this? – Alexey Jul 27 '12 at 14:05
-
4Linux/UNIX shared memory segments comes to mind. You can do things with memory mapping files though anyway which persists across reboots. Obviously you can't `new[]` to allocate things, but you can use a custom allocator (ugly) or placement new if you're careful. See for example [boost interprocess](http://www.boost.org/doc/libs/1_50_0/doc/html/interprocess/allocators_containers.html) – Flexo Jul 27 '12 at 14:09
-
I've noticed this happening when allocating memory on the GPU. Although I'm not sure that this is a reliable 'feature'. I don't really understand why this happens either. – sav Jun 30 '14 at 07:38
3 Answers
No, all memory is reclaimed by the os on process termination. You have to save stuff you want to a file.

- 12,709
- 2
- 32
- 59
-
That's not necessarily true. If you are running on hardware that doesn't have an MMU then all your memory is physical memory and your value will stay in memory until you or someone else changes it. Of course, you need to also know the memory map so you can put it somewhere that will be safe... – Jerry Jeremiah Sep 10 '20 at 02:03
It's not possible. You have to store the data in a file or system preferences in order to access it on the next launch

- 24,218
- 13
- 61
- 90
Disclaimer: Storing the values to a file or using some framework functionality like QSettings should be preferred over the following approaches.
If You really want Your variables to remain in the memory and if You can risk to loose the values in a reboot, then ask the operating system for shared memory.
If You have a POSIX-compliant platform like Linux or Windows, then use the POSIX functions. To quote the manual:
POSIX shared memory objects have kernel persistence: a shared memory object will exist until the system is shut down, or until all processes have unmapped the object and it has been deleted with
shm_unlink
.
Be warned, that this introduces a kind of memory leak: Your variables will consume memory even after the termination of the application.

- 5,022
- 2
- 22
- 37