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?
Undefined behavior; in this case, it doesn't need to
dereference a (print is non-virtual), so it may well
"work" without generating an error. A good compiler
could issue a diagnostic for this at compile time.
a = new A();
a->print();
delete a;
a->print(); // Should segfault, shouldn't it?
Undefined behavior; again, likely to "just work" but
it's allowed to do anything at all, including causing
a signal to be raised.
return 0;
}
</code>
Is this valid/correct C++? Any ideas?
No, it is not valid. But no diagnostic is required,
either at compile time or runtime -- and some bad
libraries (such as MFC) rely on a compiler allowing
such poor code.
-- James
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]