How can I detect if a program is running from within valgrind?

You should look at this page from the Valgrind manual, it contains a RUNNING_ON_VALGRIND macro (included from valgrind.h) which does what you want.


If one does not want to include valgrind.h (which requires an autoconf test or similar) or use a wrapper, here's a heuristic for Linux (and other systems using ELF?): test the value of the LD_PRELOAD environment variable since Valgrind works by preloading libraries. I use the following test in C to check whether LD_PRELOAD contains the string "/valgrind/" or "/vgpreload":

int tests_run_within_valgrind (void)
{
  char *p = getenv ("LD_PRELOAD");
  if (p == NULL)
    return 0;
  return (strstr (p, "/valgrind/") != NULL ||
          strstr (p, "/vgpreload") != NULL);
}

Other systems might have a similar solution. I suggest the following command to see whether the environment mentions Valgrind:

valgrind env | grep -i valgrind

Edit: In the relatively unlikely event that you are trying to do this either on macOS or on FreeBSD i386 running on an amd64 kernel then the environment variables are different.

  • macOS uses DYLD_INSERT_LIBRARIES
  • FreeBSD uses LD_32_PRELOAD (ONLY for i386 on amd64, not amd64 on amd64 or i386 on i386).

Plain LD_PRELOAD should work for all Linux and Solaris variants.