Dumping memory to file

前端 未结 5 560
囚心锁ツ
囚心锁ツ 2021-01-05 11:57

I\'ve got a part of my memory that I want to dump to a file. One reason is to save the information somewhere, and another is to read it again when my program restarts.

5条回答
  •  北海茫月
    2021-01-05 12:36

    As long as the data you are dumping out contains no pointers, just dumping it out like that will work. (HINT: Use the calls that can write long sequences of data all in one go to cut time.) The only thing to watch out for is if you're writing out integers or floating point numbers and reading them back in on a machine with a different architecture (e.g., big endian instead of little endian). That might or might not be a concern for you.

    But if you've got pointers inside, you've got a problem. The problem is that you cannot (well, cannot easily) guarantee that you'll get the data loaded back at the same position in the receiving process's virtual memory space. What's more, if you have data that has pointers to things that you're not saving (e.g., a stray FILE*) then you've got to think about what to do to resynthesize a valid replacement at that point. Such serialization is deeply non-trivial, and requires writing code that has knowledge of exactly what you're saving and loading.

    There is a way to simplify serialization a little when you've only got pointers within the contiguous data being saved and are always going to restore on the same architecture. Dump out the memory as before, but put a prefix descriptor on that says at least the length of the data and the number of pointers within, then also save (at the end) a table of exactly where (as offsets within the data) the pointers are and where the start of all the data was. You can then restore by reading the data in and performing address arithmetic to correct all the pointers, i.e., you can work out what offset relative to the start of the original data they were pointing to – as a char*, not the original type – and make sure that they point to the same offset relative to the address of the whole data after reloading. This is a somewhat gross hack and is formally not the most portable thing ever, but within the constraints outlined at the beginning of this paragraph I'd expect it to work. However you'll also have a really non-portable serialization format; do not count on it at all for any sort of persistent archival use!

提交回复
热议问题