PDA

View Full Version : QTestLib doesn't recognize NULL pointers?



entonjackson
11th October 2011, 17:26
Hello, i have a strange issue.

I'm having a testclass in which i tried to make a test fail, by letting an Object Pointer point to NULL and after that, calling a method on that Pointer like this...



HelloWorld *obj = NULL;
obj->hello()
QCOMPARE(obj->hello(), QString("Hello World!"));


Actually, the above is the code of my first test method.
the strange is, that it never fails... compiler compiles, and after running it, it says always PASSED.

what am i understanding wrong??

wysota
11th October 2011, 19:15
That's hardly possible, this code should crash. Show your actual code. If that's the actual code then the only explanation is that it is never ran.

stampede
11th October 2011, 21:23
It depends on what you are doing in the hello() method, if you don't access the object's data members, the code can run without a crash. For example, this does not crash (g++ 4.5.2):


#include <iostream>

class Test{
public:
void test(){
std::cout << "method called\n";
}
};

int main(){
Test * t = NULL;
t->test();
return 0;
}

entonjackson
12th October 2011, 08:58
Ok, this sounds logical.
I'm accessing nothing class-specific in that method. I'm just returning a new QString Object...



QString HelloWorld::hello()
{
return "Hello World!";
}


So... i've just tested it with this:



QString HelloWorld::hello()
{
_string = "Hello World!";
return _string;
}


...while _string is a member of HelloWorld class. And now it crashes, like it should!

Wondering if the compiler is optimizing the return "Hello World"; from the first hello() method out, and that is the reason no crash occures.
Or what other reason there is, why there's no error at runtime...?

Thank you!

wysota
12th October 2011, 09:09
No crash occurs because the compiler never tries to dereference "this" when inside the hello() method. If you make that method virtual, it will start crashing.

entonjackson
12th October 2011, 14:10
Ok!
Thanks a lot!