Declaration of variable causes segmentation fault

前端 未结 2 875
无人共我
无人共我 2020-12-17 19:19

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, define

相关标签:
2条回答
  • 2020-12-17 19:44

    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.

    0 讨论(0)
  • 2020-12-17 19:48

    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.

    0 讨论(0)
提交回复
热议问题