G ++ generated code question

Dear g ++ hackers, I have the following question.

When some data of an object is overwritten by a faulty program, why does the program end up failing to destroy that object with a double free error? How does he know if the data is corrupted or not? And why does this lead to double free?

+1


source to share


1 answer


Usually it is not that the memory of the object is being overwritten, but some part of the memory outside the object. If it hits malloc control structures, they will be free when they access them and try to do strange things based on the damaged structure.

If you were really just overwriting the object's memory with stupid things, you wouldn't know that malloc / free. Your program might crash, but for different reasons.



Take a look at valgrind . It is a tool that emulates the processor and monitors every memory access for anomalies (eg trying to rewrite malloc control structures). It is very easy to use, most of the time you just run your program inside valgrind adding valgrind

to the shell and it will save you a lot of pain.

For C ++: always make sure you use new with delete, and thus new [] with delete []. Never mix them up. Bad things will happen, often similar to what you describe (but valgrind would warn you).

+3


source







All Articles