0

How to programmatically trigger a SIGSEGV on macos?

I have:

  int i = 0;
  int * ip = &i;
  while (true) {
    *ip++ = 0;
  }

However, on Macos, this causes "EXC_BAD_ACCESS", not "SIGSEGV".

igbgotiz
  • 892
  • 1
  • 8
  • 28
  • Probably of interest: https://stackoverflow.com/questions/24559347/exc-bad-access-vs-segmentation-fault-are-both-same-practically – Jeremy Friesner Apr 13 '23 at 23:33

1 Answers1

1

Here's a little C program that (on my Mac, anyway) demonstrates that it is in fact SIGSEGV that is being raised, regardless of what MacOS is calling it. This program installs a signal handler for SIGSEGV, then invokes some undefined behavior to provoke a segmentation fault into occurring, in order to see if the handler does in fact get executed.

On my machine, I see this when I run the program:

$ g++ temp.cpp
$ ./a.out 
Signal 11 detected!

Here's the program's source:

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>

static void MyHandlerFunc(int sigNum)
{
   // it's not really allowed to call printf() here,
   // but I'm gonna cheat and do it anyway just for fun
   printf("Signal %i detected!\n", sigNum);
   exit(10);
}

int main(int argc, char ** argv)
{
   struct sigaction newact;
   sigemptyset(&newact.sa_mask);
   newact.sa_flags   = 0;
   newact.sa_handler = MyHandlerFunc;
   if (sigaction(SIGSEGV, &newact, NULL) == -1)
   {
      perror("sigaction");
      return 10;
   }

   // Let's try to cause a segmentation fault
   int * x = NULL;
   while(*x)
   {
      (*x)++;
      x++;
   }

   return 0;
}

Note that if I comment out the sigaction() call in the program, then running the program gives this output:

$ ./a.out 
Segmentation fault: 11

... which is likely more in line with the output you were expecting.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234