Make a piece of heap memory read-only [closed]
If I have a database application in C++. When the data size is small, it's easy to debug for bugs. But when the data size becomes huge, and relationship becomes complex, the bug is very hard to debug, or hard to find the root cause of it. Sometimes the callstack can't tell you enough information to find the root cause, because the memory has been collapsed. It's very easy the memory of one component is written by other component. Only when the first component visit that memory, we met the crash, but it's too late.
The difficulty to find the root cause is proportional to the size of the handling data.
I am wondering if there is any tricks to predicate the risk, and protection code for avoid illegal memory written.
C++ pointer is a powerful tool, but it's also the high risk to use it. Any code could use the pointer to write/update the memory any开发者_运维技巧time. When one code write a memory, no other class object know it unless the class visit that memory,then find the value is already invalid, crashed.
If A hold a pointer to B, then some code write that memory to make the value to C. Then when A use the B pointer to do something, invalid pointer.
I want to know, maybe it's impossible, if there some way to avoid this situation. Could we add some protection code there.
One method I thought could be is I could make the memory to be writable before change, after change make it readable. So other code can't write it, otherwise crash. This would help me to find the issue earlier.
Is there some way to make a piece of heap memory read-only?
Platform is windows. I hope I could use some switch in the code to control it's access right.
I think the general trick here is separation of concerns. If you can write small, independent pieces of code that you can have confidence in, and then connect these building blocks together in useful ways, it's a lot easier to have confidence in the results.
Confidence in the individual building blocks (classes, functions etc) can be boosted by unit tests. This counts double for code that you expect to change :)
Without seeing any code it's a bit difficult to provide any directed suggestions, but my guess is that you have a high degree of coupling and low cohesion between your components, and your data encapsulation/ownership may also need work. There is a lot of information available through google on how you might deal with these kinds of issues.
精彩评论