Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print out value of stack pointer

How can I print out the current value at the stack pointer in C in Linux (Debian and Ubuntu)?

I tried google but found no results.

like image 658
Juicy Avatar asked Nov 18 '13 22:11

Juicy


People also ask

How do I print the value of a pointed pointer?

You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.

What is the value of stack pointer?

The stack pointer (SP) points to the top element of the stack. The current value of SP is (016E)hex. The CALL instruction is of two words, the first word is the op-code and second word is the starting address of the subroutine (one word = 2 Bytes).

What is stack pointer in C?

What is stack pointer? A stack pointer is a small register that stores the memory address of the last data element added to the stack or, in some cases, the first available address in the stack.


2 Answers

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

like image 186
JaredPar Avatar answered Sep 27 '22 21:09

JaredPar


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.

like image 20
duedl0r Avatar answered Sep 27 '22 19:09

duedl0r