Re: Invalid pointer dereference, or not?
loose AT astron DOT nl wrote:
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?
a = new A();
a->print();
delete a;
a->print(); // Should segfault, shouldn't it?
return 0;
}
</code>
Is this valid/correct C++? Any ideas?
The code is valid (well-formed), but has undefined behaviour.
As for why it doesn't segfault (whatever that means to you), there
is no requirement to do anything specific as far as undefined
behaivour goes.
Now, if I were to speculate as to why the program can actually run
(just like somebody might expect), the explanation is relatively
simple: the 'print' member function makes no attempt to access any
member data (there is no member data to access, actually), so no
dereferencing of the invalid pointer 'a' is actually performed.
But that's happening only on your system. There is no guarantee
that the same behaviour would be observed on any other system, and
that's why the behaviour cannot be defined one way or another.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]