When and why would such memory copy occur (in C and C++)?
By no means an exhaustive list, but examples would include:
- Calls for explicit copies like
strncpy()
, memcpy()
- Passing arguments by value causes them to duplicated (generally on the stack)
- Variable assignments for structs and classes (not pointers) cause a copy.
- You also have no guarantee what the runtime's memory manager does or doesn't do. Memory that has been freed might still be sitting there, in whole or in part.
- Data can be also swapped from memory out to disk by the operating system (virtual memory), cause a copy on disk.
Is there any solutions to prevent it? Both on program level and compiling level
Probably the most scientific answer is: No. If the user has full access to the machine (including physical access) you can't entirely prevent someone from finding a way to get at memory of your program. But you certainly can make it harder.
One approach that comes to mind is the keep the information obfuscated in some way until the last possible moment and decode only the specific thing you need one piece at a time, being careful to fill that memory with garbage afterward.
If someone is trying to scrape the memory of your program to look for sensitive information, you can probably slow them down a lot by making it (nearly) all random-looking bytes that are only decoded in very small pieces. This would basically force them to decompile/disassemble your program to figure out exactly what encoding you were doing and how in order to get at the data. Combine this with a binary code obfuscation tool and this becomes a major hassle.
Again, it's not impossible to circumvent this approach, but it's definitely harder.