简体   繁体   English

这段代码在哪里?

[英]Where does this code segfault?

My question, now reduced to a - hopefully - minimal example, is why the following code segfaults. 我的问题,现在简化为 - 希望 - 最小的例子,是以下代码段错误的原因。

It can of course be seen as a duplicate of the proposed question, provided you have found the latter. 如果您找到后者,它当然可以被视为提议问题的副本。 The problem is, I failed to find the question in my initial search and so may many newbies, not knowing the cause of error. 问题是,我在初始搜索中找不到问题,所以可能有很多新手,不知道错误的原因。 I propose this as a duplicate I could have found: 我建议将此作为我可以找到的副本:

Segmentation Fault before main 主要之前的分段故障

but the problem description is very long, so that I believe my minimised and much shorter code might be better for illustrating the problem. 但问题描述很长,所以我相信我的最小化和更短的代码可能更好地说明问题。 In any case, it is a duplicate. 在任何情况下,它都是重复的。 I propose the moderators set this as a duplicate and set a link from the second possible duplicate to the first one. 我建议主持人将其设置为副本,并设置从第二个可能副本到第一个副本的链接。

#include <stdio.h>


/* Parameters */
#define N 3072  
#define LDA N

/* Main program */
int main()  {
        printf( "-----------------------------------------------> Entry main.\n" );
        /* Local arrays */
    double a[LDA*N];
        printf( "-----------------------------------------------> End main.\n" );
return 0;        
}

A segfault does not occur when 当发生段错误时不会发生

#define N 3072

is replaced by 被替换为

#define N 5

Neither does a segfault occur when the line 线路时也不会发生段错误

double a[LDA*N];

is omitted. 省略。

I am especially confused by the observation that the segfault occurs without reaching 我特别感到困惑的是,在没有达到的情况下发生了段错误

printf( "-----------------------------------------------> Entry main.\n" );

which I put directly at the beginning of main. 我直接放在主要的开头。

For completeness, I run the code like this: 为了完整性,我运行如下代码:

ludi@ludi-M17xR4:~/Desktop/tests$ g++ -o minicombo.x minicombo.cc && ./minicombo.x

The segfault is likely due to the array definition double a[LDA*N]; segfault可能是由于数组定义double a[LDA*N]; . This creates a 72MB array with automatic storage duration ("on the stack"). 这将创建一个具有自动存储持续时间的72MB阵列(“在堆栈上”)。 You have several alternatives. 你有几种选择。

  1. Use std::vector<double> created with the desired size or resize() member function. 使用使用所需大小或resize()成员函数创建的std::vector<double>
  2. Dynamic allocation with std::unique_ptr<double[]> or new[]/delete[] . 使用std::unique_ptr<double[]>new[]/delete[]动态分配。 Beware, manual memory management is fraught with peril. 请注意,手动内存管理充满了危险。
  3. Make the array static or global. 使数组static或全局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM