Nate
Nate

Reputation: 155

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:

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.

Upvotes: 5

Views: 9448

Answers (2)

ugoren
ugoren

Reputation: 16449

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.

Upvotes: 4

dreamlax
dreamlax

Reputation: 95405

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);
}

Upvotes: 5

Related Questions