Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

c - Declaration of variable causes segmentation fault

I don't understand the reason for a segmentation fault error in my program. The code is available here

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];

The program works well, but when I declare a second PclImage, I get a segmentation fault as soon as I launch the program.

For example, if at line 30 of the first file I add PclImage bgPcl; the program immediately crashes.

Can anyone help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 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).

When you have such large objects, you should allocate them dynamically (using malloc and friends) or, if you aren't concerned with reentrancy, statically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...