Debugging a memory access violation
You're on Windows.
This means that if the error happens on a machine with Visual Studio installed, you'll have an option to open it to debug the error and thus know the exact line where the error happens.
Studying the code
Too little code to answer correctly. Still, one can guess:
delete m_p1;
Are you sure m_p1 is a pointer to a valid object ? (allocated with new
, etc.)
A *a = new A();
You must review the constructor for A. Perhaps it does something wrong.
a->b = *c;
This is the line I suspect the more : If c
is an invalid pointer (either NULL, or points to some random address), dereferencing it to put the result inside a->b
could provoke the error
m_p1 = a; --> strange code.
The funny fact is that this is the only line of code which can't produce the error you got : a is a pointer containing an address, and you can copy addresses around. It's using this address (dereferencing the pointer, etc.) that causes memory access violation.
About m_p1 = a;
This code is not so strange, but it proves you still have issues with pointers.
In C, C++, Java, etc., when you allocate a memory (to put things inside, to create an object, etc.), the allocator (new, malloc, whatever...) will give you a handle. In Java/C#, this is called a reference, and in C/C++, this is a pointer.
Let's imagine you'll want to go to a concert, and the seat number is where you'll sit, and the seat
is the real object, where you'll sit and enjoy the show.
m_p1
is a paper in your wallet where you want to have exact seat number
a
is a temporary paper, a napkin, whatever...
delete m_p1
is when you resell your place, so the seat number you bought before is not valid anymore. You should not use it anymore.
a = new A()
is when you buy another place, so you have in a
another valid seat number, but for whatever reason, instead of writing in in your wallet (m_p1
), you'll write it on a napkin.
m_p1 = a
is when you eventually copy the seat number from some napkin to your wallet.
The point is that you have:
- pointers, which contains memory addresses (the pointer value)
- memory addresses, where you have real objects
Destroying a real object through delete
won't destroy the pointer. It only makes the address invalid (the address didn't change. It's just not valid anymore). So you can put in a pointer whatever address you want, even reuse the pointer to contain the address of another object.