Re: Invalid pointer dereference, or not?
loose AT astron DOT nl wrote:
Hi all,
I was quite baffled to see this (simplified) program run without
segfaults, and without valgrind complaining about invalid memory
reads.
<code>
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
void print() const { cout << "Hello World" << endl; }
};
int main()
{
A* a;
a->print(); // Should segfault, shouldn't it?
No. not necessarily. You have undefined behavior. UB can be anything,
including performing "as expected" (whatever that is), segfaulting,
reformatting your hard drive, calling NORAD and starting WWIII, or even
killing the crew and locking the pod bay doors.
a = new A();
a->print();
delete a;
a->print(); // Should segfault, shouldn't it?
No. UB. See above.
return 0;
}
</code>
Is this valid/correct C++? Any ideas?
It is syntactically correct C++. However, the program exhibits undefined
behavior.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]