Listing 2: Code for scanning through the heap portion of memory and solution to the guard region problem

static jmp_buf jmpenv;
static void segvHandler(int signo)
{
  longjmp(jmpenv, 1);
}

static struct sigaction oaction;

#define SET_SIGSEGV_ACTION { \
  struct sigaction action; \
  action.sa_sigaction = NULL; \
  action.sa_handler = segvHandler; \
  action.sa_mask = 0; \
  action.sa_flags = SA_RESTART; \
  sigaction(SIGSEGV, &action, &oaction); }

#define RESET_SIGSEGV_ACTION \
  sigaction (SIGSEGV, &oaction, NULL);
#define SETJMP(e) setjmp(e)

static void memtrackCheckLeaks(void)
{
  void** scanPoint;

  /* check initialized data, BSS, and heap */
  SET_SIGSEGV_ACTION;
  for(scanPoint = (void**)&_fdata; 
      scanPoint < (void**)sbrk(0); 
      ++scanPoint)
  {
    if (SETJMP(jmpenv) == 0)
    {
      for(; scanPoint < (void**)sbrk(0); ++scanPoint)
      {
        if (scanPoint == (void**)&memList[0]) 
        {
          scanPoint = (void**)&memList[memListAllocated];
        }
        else if (*scanPoint >= lowAddress && *scanPoint <= 
          highAddress)
        {
          AllocRec* mem;
          if ((mem = memList_find(*scanPoint)) != NULL)
          {
            mem->refExists |= REF_TO_START;
          }
          else if ((mem = memList_findInRange(*scanPoint)) != NULL)
          {
            mem->refExists |= REF_TO_WITHIN;
          }
        }
      }
    }
  }
  RESET_SIGSEGV_ACTION;