Print out value of stack pointer

One trick, which is not portable or really even guaranteed to work, is to simple print out the address of a local as a pointer.

void print_stack_pointer() {
  void* p = NULL;
  printf("%p", (void*)&p);
}

This will essentially print out the address of p which is a good approximation of the current stack pointer


There is no portable way to do that.

In GNU C, this may work for target ISAs that have a register named SP, including x86 where gcc recognizes "SP" as short for ESP or RSP.

// broken with clang, but usually works with GCC
register void *sp asm ("sp");
printf("%p", sp);

This usage of local register variables is now deprecated by GCC:

The only supported use for this feature is to specify registers for input and output operands when calling Extended asm

Defining a register variable does not reserve the register. Other than when invoking the Extended asm, the contents of the specified register are not guaranteed. For this reason, the following uses are explicitly not supported. If they appear to work, it is only happenstance, and may stop working as intended due to (seemingly) unrelated changes in surrounding code, or even minor changes in the optimization of a future version of gcc. ...

It's also broken in practice with clang where sp is treated like any other uninitialized variable.


In addition to duedl0r's answer with specifically GCC you could use __builtin_frame_address(0) which is GCC specific (but not x86 specific).

This should also work on Clang (but there are some bugs about it).

Taking the address of a local (as JaredPar answered) is also a solution.

Notice that AFAIK the C standard does not require any call stack in theory.

Remember Appel's paper: garbage collection can be faster than stack allocation; A very weird C implementation could use such a technique! But AFAIK it has never been used for C.

One could dream of a other techniques. And you could have split stacks (at least on recent GCC), in which case the very notion of stack pointer has much less sense (because then the stack is not contiguous, and could be made of many segments of a few call frames each).

Tags:

Linux

C

Stack