【问题标题】:how to know a c program's stack overflows?如何知道 c 程序的堆栈溢出?
【发布时间】:2018-01-09 17:12:52
【问题描述】:

我在 c 中模拟一个问题(3d Ising 模型),但是当问题变大时,程序停止并出现以下错误:

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

在程序中我有一个递归函数可以完成所有工作,我怀疑错误是由于堆栈溢出(在递归函数中),但我不知道如何确定。

如果是因为堆栈溢出,有什么办法可以在不改变程序设计的情况下解决这个问题?

我正在使用 Clion IDE。

/*
 * recursive function to form Wolff Cluster(= WC)
 */
void grow_Wolff_cluster(lattic* l, Wolff* wolff, site *seed){

    /*a neighbor of site seed*/
    site* neighbor;

    /*go through all neighbors of seed*/
    for (int i = 0 ; i < neighbors ; ++i) {


        neighbor = seed->neighbors[i];

        /*add to WC according to the Wolff Algorithm*/
        if(neighbor->spin == seed->spin && neighbor->WC == -1 && ((double)rand() / RAND_MAX) < add_probability)
        {
            wolff->Wolff_cluster[wolff->WC_pos] = neighbor;
            wolff->WC_pos++;                  // the number of sites that is added to WC
            neighbor->WC = 1;          // for avoiding of multiple addition of site
            neighbor->X = 0;


            ///controller_site_added_to_WC();


            /*continue growing Wolff cluster(recursion)*/
            grow_Wolff_cluster(l, wolff, neighbor);
        }
    }
}

【问题讨论】:

  • 在调试器中捕获崩溃。查看函数调用堆栈。如果它只有grow_Wolff_cluster 调用,那么你有一个堆栈溢出。
  • 递归算法通常会产生优雅的解决方案,但实际上由于这些原因它们可能很危险,通常应该避免使用,除非您确定它只会递归安全数量的次。我不知道你在这里做什么,但你可能最好以非递归方式重新实现它。
  • ericlippert.com/2014/03/05/how-to-debug-small-programs stackoverflow.com/questions/2069367/how-to-debug-using-gdb 应该是有用的读物​​。也许还有ericlippert.com/2014/03/21/find-a-simpler-problem 回到可靠工作的坚实基础,然后再次开始增加。
  • 最基本的方法:将一些 printfs 放在程序的关键点上,看看会显示什么。
  • 是的,它充满了递归函数,它太慢了,我无法导航以查看其中有多少。但毕竟我有一个递归函数,我希望看到很多递归函数

标签: c debugging stack-overflow


【解决方案1】:

使用 GDB 调试器并查看调用堆栈。

gdb main
r
bt

【讨论】:

  • 谢谢我试试这个,GDB是默认安装的?!
猜你喜欢
  • 2018-06-24
  • 2013-12-12
  • 2010-11-05
  • 2012-12-20
  • 2011-03-02
  • 2014-01-17
  • 1970-01-01
  • 2015-09-08
相关资源
最近更新 更多