catching segfault using try_ catch

Adam D Ruppe destructionator at gmail.com
Tue Jul 13 17:49:54 UTC 2021


On Tuesday, 13 July 2021 at 16:52:43 UTC, seany wrote:
> What will it return to me?

true if it succeeded.

> I want to catch the segfault and a segfault has occured, I want 
> run a different code at that point.

You mean transparently rerun some code? That's better done with 
the lowlevel sigaction handler.

But if you just want to standard try/catch then do something in 
the catch block, this is fine.


import etc.linux.memoryerror;

void main() {
         registerMemoryErrorHandler();
         int* a;
         try {
                 *a = 4;
         } catch(Throwable e) {
                 import std.stdio;
                 writeln("Caught");
         }
}


It can be used on ldc2 too but it isn't as reliable since ldc 
considers null access to be undefined behavior anyway and thus 
may optimize out your catch....

You also need to compile in the module with ldc so build it like

$ ldc2 seg.d ~/d/ldc/import/etc/linux/memoryerror.d

just including the memoryerror file o the command line lets it 
link.


More information about the Digitalmars-d-learn mailing list