Checking if a pointer is allocated memory or not

前端 未结 18 1461
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 07:30

Can we check whether a pointer passed to a function is allocated with memory or not in C?

I have wriiten my own function in C which accepts a character pointer -

18条回答
  •  悲哀的现实
    2020-11-28 08:06

    The below code is what I have used once to check if some pointer tries to access illegal memory. The mechanism is to induce a SIGSEGV. The SEGV signal was redirected to a private function earlier, which uses longjmp to get back to the program. It is kind of a hack but it works.

    The code can be improved (use 'sigaction' instead of 'signal' etc), but it is just to give an idea. Also it is portable to other Unix versions, for Windows I am not sure. Note that the SIGSEGV signal should not be used somewhere else in your program.

    #include 
    #include 
    #include 
    #include 
    
    jmp_buf jump;
    
    void segv (int sig)
    {
      longjmp (jump, 1); 
    }
    
    int memcheck (void *x) 
    {
      volatile char c;
      int illegal = 0;
    
      signal (SIGSEGV, segv);
    
      if (!setjmp (jump))
        c = *(char *) (x);
      else
        illegal = 1;
    
      signal (SIGSEGV, SIG_DFL);
    
      return (illegal);
    }
    
    int main (int argc, char *argv[])
    {
      int *i, *j; 
    
      i = malloc (1);
    
      if (memcheck (i))
        printf ("i points to illegal memory\n");
      if (memcheck (j))
        printf ("j points to illegal memory\n");
    
      free (i);
    
      return (0);
    }
    

提交回复
热议问题