Unit tests and segfaults

Alex Rønne Petersen alex at lycus.org
Thu Dec 6 02:41:33 PST 2012


On 06-12-2012 11:31, Jonathan M Davis wrote:
> On Thursday, December 06, 2012 09:02:29 Russel Winder wrote:
>> What is the right idiom for testing that a function call does segfault
>> when you want it to?
>
> Why would you _want_ a function to segfault? That's like asking how to write a
> function which tests that a computer is off after you pull the plug.
>
> Regardless, since segfaults pretty much just kill the program, I don't think
> that you can do much. You could install a signal handler to catch the
> segfault, but segfaults aren't exceptions, and AFAIK, it's not possible to
> continue the program (or at least that thread) in any meaningful way at that
> point. It's also the case that the signal handler is completely separate from
> the function being called or the code which is testing that function, making
> it so that you can't continue the execution of your test code, and you have no
> way of really knowing whether than segfault came from where you wanted it to.
> You could set a variable before the function and unset it afterwards so that
> the signal handler could test its state (with the idea that if that variable
> has been set, the segfault came from that code), but if any other threads are
> running, _they_ could have caused any segfaults which occur (regardless of the
> state of that variable), and even if you have only one thread, there's no way
> to know that the segfault was generated from the exact spot that you intended
> rather than a stray null pointer or whatnot in the code being tested.
>
> - Jonathan M Davis
>

It is actually possible to continue after a segmentation fault (see the 
new, experimental etc.linux.memoryerror module in druntime) and most 
virtual machines do this to handle null pointer errors (contrary to 
popular belief, they don't check for nulls everywhere). It's even 
possible to do cleanly.

It's just not portable. At all.

-- 
Alex Rønne Petersen
alex at lycus.org
http://lycus.org


More information about the Digitalmars-d-learn mailing list