问题描述
我不明白我的程序中出现分段错误错误的原因.代码可在这里
I don't understand the reason for a segmentation fault error in my program.The code is available here
在第 29 行,我声明了一个 PclImage
变量,用 typedef 定义,就像一个结构数组.PclImage
类型的定义如下(来自src/libMyKinect.h 文件):
At line 29 I declare a PclImage
variable, defined with typedef like an array of struct.The definition of PclImage
type is the following (from src/libMyKinect.h file):
typedef struct {
int valid;
float x;
float y;
float z;
unsigned char blue;
unsigned char green;
unsigned char red;
} Point3d;
typedef Point3d PclImage[480][640];
程序运行良好,但是当我声明第二个 PclImage
时,我一启动程序就遇到分段错误.
The program works well, but when I declare a second PclImage
, I get a segmentation fault as soon as I launch the program.
例如,如果我在第一个文件的第 30 行添加 PclImage bgPcl;
程序会立即崩溃.
For example, if at line 30 of the first file I add PclImage bgPcl;
the program immediately crashes.
谁能帮帮我?
推荐答案
如果将 PclImage
声明为局部变量(在堆栈上),则很可能由于堆栈溢出.
If you declare a PclImage
as a local variable (on the stack), you are likely to get a segmentation fault due to a stack overflow.
PclImage
是一个包含 307,200 个元素的数组,每个元素(可能)大小约为 20 字节,因此整个数组的大小约为 6MB.堆栈大到足以包含其中两个数组的可能性很小.它甚至可能不够大,无法容纳一个(作为一个非常普遍的规则,在大多数桌面操作系统上,假设您至少有 1MB 可用堆栈空间通常是安全的).
PclImage
is an array with 307,200 elements, each of which is (likely) about 20 bytes in size, so the whole array is something around 6MB in size. It's highly unlikely that the stack is large enough to contain two of those arrays; it might not even be large enough to contain one (as a very general rule, it's usually safe on most desktop OSes to assume that you have at least 1MB of stack space available).
当你有这么大的对象时,你应该动态地分配它们(使用 malloc
和朋友),或者,如果你不关心重入,静态地.
When you have such large objects, you should allocate them dynamically (using malloc
and friends) or, if you aren't concerned with reentrancy, statically.
这篇关于变量声明导致分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!