[英]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. 正如标题所说,我想在我的C程序中打印堆栈的内容。
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 我做了一个简单的汇编(helper.s)文件,其中包含一个返回我的ebp寄存器地址的函数和一个返回我的esp寄存器地址的函数
.globl get_esp get_esp: movl %esp, %eax ret # get_ebp is defined similarly, and included in the .globl section
get_esp ()
and get_ebp ()
functions from my C program ( fpC = get_esp ();
where fpC is an int) get_esp ()
和get_ebp ()
函数( fpC = get_esp ();
其中fpC是一个int) fprintf (stderr, "%x", fcP);
) fprintf (stderr, "%x", fcP);
) fprintf (sderr, "%d", *fcP);
and fprintf (sderr, "%x", *((int *)fcP));
, among other methods). fprintf (sderr, "%d", *fcP);
和fprintf (sderr, "%x", *((int *)fcP));
以及其他方法)。 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.
EDIT2:这是家庭作业。
If your utilising a GNU system, you may be able to use GNU's extension to the C library for dealing backtraces, see here . 如果您使用GNU系统,您可以使用GNU的C库扩展来处理回溯,请参见此处 。
#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. get_esp
返回esp
因为它在函数内。 But this isn't the same as esp
in the calling function, because the call operation changes esp
. 但这与调用函数中的
esp
,因为调用操作会改变esp
。
I recommend replacing the function with a piece of inline assembly. 我建议用一个内联组件替换该功能。 This way
esp
won't change as you try to read it. 这样
esp
在你尝试阅读它时不会改变。
Also, printing to sderr
wouldn't help. 此外,打印到
sderr
无济于事。 From my experience, stderr
works much better. 根据我的经验,
stderr
工作得更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.