Alex Rivera | Logout

Declaration of variable causes segmentation fault

Asked 2010-12-28T16:20:49.203
11

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?

Edit
Report

1 Answer

1

I agree with James that allocating those large arrays on the stack is most likely the cause. However, each PclImage adds up to only about 6Meg each. Unless you are operating in a limited memory environment, this should be doable. I've allocated far larger arrays on the stack before. Even on embedded systems.

James' suggestion of using malloc probably will fix it (worth a try just to verify the issue). However, I find it a good policy to avoid dynamic allocation when possible. Possible alternatives to malloc would be to declare the arrays in external context, or to increase your thread's stack size. User-created processes and/or threads often have fairly small stacks allocated to them by default. It can be a fairly simple matter to find where that is set and give it a large enough stack for your needs.

For example, if this is run from a thread created with the Windows CreateThread() routine, the second parameter controls the stack size. If you default it with a 0 (as most folks do), it takes the default stack size. As near as I can tell, that's "only" 1 MB.

answered 2010-12-28T16:34:12.550

Your Answer