【发布时间】:2011-11-01 06:28:00
【问题描述】:
这里我想解决这段代码中的堆栈溢出问题。 在这段代码中,我递归调用函数 p 350000 次,所以我得到了分段错误 当我删除 350000 并放入 300000 时,它工作正常 这里的分段错误是因为我多次递归调用函数 p 或调用递归函数太深。
这不起作用,因为我接受了if(i != 350000)。
它的止损点可能在 300000 到 327480 这个范围内。我测试了 10 次
代码:
#include <stdio.h>
void p(char *, int);
int main()
{
char *a = "HI";
int b = 10;
p(a, b);
printf("\nComplete");
return 0;
}
void p(char *a, int b)
{
static long int i = 0;
if (i != 350000)
{
printf("\n%ld \t at Hi hello", i);
i++;
p(a, b);
} else
{
return;
}
}
当我使用 valgrind 工具检查此代码时,valgrind 会报告这样的错误
==9236== Stack overflow in thread 1: can't grow stack to 0x7fe801ff8
==9236==
==9236== Process terminating with default action of signal 11 (SIGSEGV)
==9236== Access not within mapped region at address 0x7FE801FF8
==9236== at 0x4EA012E: _IO_file_write@@GLIBC_2.2.5 (fileops.c:1276)
==9236== If you believe this happened as a result of a stack
==9236== overflow in your program's main thread (unlikely but
==9236== possible), you can try to increase the size of the
==9236== main thread stack using the --main-stacksize= flag.
==9236== The main thread stack size used in this run was 8388608.
==9236== Stack overflow in thread 1: can't grow stack to 0x7fe801ff0
==9236==
==9236== Process terminating with default action of signal 11 (SIGSEGV)
==9236== Access not within mapped region at address 0x7FE801FF0
==9236== at 0x4A2269F: _vgnU_freeres (vg_preloaded.c:58)
==9236== If you believe this happened as a result of a stack
==9236== overflow in your program's main thread (unlikely but
==9236== possible), you can try to increase the size of the
==9236== main thread stack using the --main-stacksize= flag.
==9236== The main thread stack size used in this run was 8388608.
请帮帮我,我真的想要这个问题的解决方案。而且我无法从我的代码中删除函数的递归调用。
【问题讨论】:
标签: c memory memory-management stack-overflow