检测堆栈已满 [英] Detecting that the stack is full

查看:28
本文介绍了检测堆栈已满的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写 C++ 代码时,我了解到使用堆栈来存储内存是一个好主意.

When writing C++ code I've learned that using the stack to store memory is a good idea.

但最近我遇到了一个问题:

But recently I ran into a problem:

我进行了一个实验,其中的代码如下所示:

I had an experiment that had code that looked like this:

void fun(const unsigned int N) {
    float data_1[N*N];
    float data_2[N*N];

    /* Do magic */
}

代码随机出现了一个分段错误,我不知道为什么.

The code exploted with a seqmentation fault at random, and I had no idea why.

事实证明,问题是我试图在我的堆栈上存储很大的东西,有没有办法检测到这一点?或者至少检测到它出错了?

It turned out that problem was that I was trying to store things that were to big on my stack, is there a way of detecting this? Or at least detecting that it has gone wrong?

推荐答案

float data_1[N*N];
float data_2[N*N];

这些是可变长度数组 (VLA),因为 N 不是常量表达式.参数中的 const-ness 仅确保 N 是只读的.它不会告诉编译器 N 是常量表达式.

These are variable length arrays (VLA), as N is not a constant expression. The const-ness in the parameter only ensures that N is read-only. It doesn't tell the compiler that N is constant expression.

VLA 仅在 C99 中允许;在其他版本的 C 和所有版本的 C++ 中,它们都是不允许的.但是,一些编译器提供 VLA 作为编译器扩展功能.如果您使用 GCC 进行编译,请尝试使用 -pedantic 选项,它会告诉您这是不允许的.

VLAs are allowed in C99 only; in other version of C, and all versions of C++ they're not allowed. However, some compilers provides VLA as compiler-extension feature. If you're compiling with GCC, then try using -pedantic option, it will tell you it is not allowed.

现在为什么你的程序给出段错误,可能是因为 stack-overflowN * N:

Now why your program gives segfault, probably because of stack-overflow due to large value of N * N:

考虑使用 std::vector 作为:

#include <vector> 

void fun(const unsigned int N) 
{
  std::vector<float> data_1(N*N);
  std::vector<float> data_2(N*N);

  //your code
}

这篇关于检测堆栈已满的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆