Suppose I have a class like
class A {
int x;
int y;
public:
getSum1() const {
return getx() + y;
}
getSum2() const {
return y + getx();
}
getx() const {
return x;
}
}
And then I have
int main(int argc, char **argv) {
A *a = 0;
switch(argc) {
case 0:
a->getsum1();
break;
default:
a->getsum2();
break;
}
return 1;
}
This program will segfault. I noticed that on my machine, when getsum1 executes, the core
dump says the segfault was caused in getx, and when getsum2 executes it says the fault happened in getsum2.
This makes sense. I have 2 questions:
1. is this behaviour specified, or is it implementation dependent?
And most importantly:
2. Could the core dump say that the segfault happened in main, when a was dereferenced? (i.e. at a->getsum*)
Thanks.
When you called those functions on a null pointer, you got undefined behavior. That’s really all that should be said; anything can happen, don’t do it.
The reason it segfaults is because there is no
Aat null. Attempting to access those members is attempting to access an invalid address. (This happens ingetxandgetSum2, hence the segfault report.)No, it cannot say the segfault happened in
mainbecause null wasn’t accessed in main. (You still entered undefined behavior in main, no doubt, but in practice it just called a function withthisset to null.) You accessed it in those functions. In practice, if a function never usesthis, it won’t crash with a null pointer.But don’t.