简体   繁体   中英

How can I print the contents of stack in C program?

I want to, as the title says, print the contents of the stack in my C program.

Here are the steps I took:

  • I made a simple assembly (helper.s) file that included a function to return the address of my ebp register and a function to return the address of my esp register

     .globl get_esp get_esp: movl %esp, %eax ret # get_ebp is defined similarly, and included in the .globl section 
  • I called the get_esp () and get_ebp () functions from my C program ( fpC = get_esp (); where fpC is an int)
  • I (successfully, I think) printed the address of my esp and ebp registers ( fprintf (stderr, "%x", fcP); )
  • I tried, and failed to, print out the contents of my esp register. (I tried fprintf (sderr, "%d", *fcP); and fprintf (sderr, "%x", *((int *)fcP)); , among other methods). My program hits a segmentation fault at runtime when this line is processed.

What am I doing wrong?

EDIT: This must be accomplished by calling these assembly functions to get the stack pointers. EDIT2: This is a homework assignment.

If your utilising a GNU system, you may be able to use GNU's extension to the C library for dealing backtraces, see here .

#include <execinfo.h>

int main(void)
{
     //call-a-lot-of-functions
}

void someReallyDeepFunction(void)
{
    int count;
    void *stack[50]; // can hold 50, adjust appropriately
    char **symbols;

    count = backtrace(stack, 50);
    symbols = backtrace_symbols(stack, count);

    for (int i = 0; i < count; i++)
        puts(symbols[i]);

    free(symbols);
}

get_esp returns esp as it is within the function. But this isn't the same as esp in the calling function, because the call operation changes esp .

I recommend replacing the function with a piece of inline assembly. This way esp won't change as you try to read it.

Also, printing to sderr wouldn't help. From my experience, stderr works much better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM