r/gcc • • 26d ago

Idea: __thread __attribute__((recurse_depth)) unsigned depth;

Example usage


#include <foo.h>

#ifndef FOO_LIMIT
#define FOO_LIMIT 8
#endif

unsigned foo_limit = FOO_LIMIT;
unsigned set_foo_limit( unsigned limit )
{
  unsigned x = foo_limit;
  foo_limit = limit;
  return x;
}

int foo(void)
{
__thread __attribute__((recurse_depth)) unsigned int depth = 0;
  if ( depth >= foo_limit )
    return -1;
  ...
  return 0;
}

When GCC compiles foo() it would insert an increment of depth at the top of foo() and a decrement before every return. Makes it easier to write code that protects against stack overflows caused by recursion.

Edit: GCC should also throw an error when the developer tries to directly modify it or grab it's address

Edit 2: GCC should also throw an error when the developer tries to initialise it to anything other than 0 or give it a signed type

1 Upvotes

0 comments sorted by