【问题标题】:Segmentation fault (core dumped) if I don't include a cout? [closed]如果我不包含 cout,则出现分段错误(核心转储)? [关闭]
【发布时间】:2017-04-15 02:27:22
【问题描述】:

我正在根据输入文件创建一个动态数组,并且在 gdc 中没有任何有用信息的情况下被抛出一个分段错误错误。 在调试时,我尝试检查 Ntot 是否被正确读取,并以某种方式修复了错误。 如果我删除 cout(如示例中所示)然后错误返回,有人知道为什么吗?

#include <iostream>
#include <math.h>
#include <fstream>
#include <stdlib.h>

using namespace std;

int main(){

double **number;

int i, Ntot;

ifstream input("initial_parameters.dat");

input >> Ntot;

//cout<<Ntot<<endl;
//uncomenting this removes the error

number = (double**)malloc(sizeof(double*) * (5));
for (int i = 1; i <= 5; i++)
    number[i] = (double*)malloc(sizeof(double) * (Ntot));

    number[1][1] = 1.;
    cout<<number[1][1]<<endl;
    number[2][1] = 2.;
    cout<<number[2][1]<<endl;
    number[3][1] = 3.;
    cout<<number[3][1]<<endl;
    number[4][1] = 4.;
    cout<<number[4][1]<<endl;
    number[5][1] = 5.;
    cout<<number[5][1]<<endl; 

return 0;

}

编辑:工作数组初始化是:

double** number = new double*[5];
for (int i = 0; i < 5; i++)
    number[i] = new double[Ntot];

【问题讨论】:

  • 为什么,哦为什么你在C++中使用malloc
  • 您有未定义的行为,因为写入分配的内存超出范围。在 c++ 中,索引从 0size - 1
  • 数组的第一个元素在索引 0 处。访问 number[5] 会导致未定义的行为。
  • 还有Ntot的值是多少?如果是&lt;=1,你会怎么做?
  • @UnholySheep Ntot 是一个正整数值,我使用的是 1000 atm

标签: c++ segmentation-fault


【解决方案1】:

从索引 0 开始分配内存,因为 C/C++ 中的索引是从 0 而不是 1。

for (int i = 0; i < 5; i++)

另外,将以上所有number[i][j] 中的i 替换为i - 1。喜欢number[1][1] = 1. by number[0][1] = 1. 等等。

另外,不要使用malloc(也不要对其结果进行类型转换!),而是使用new

number[i] = new double[Ntot];

【讨论】:

  • 在新的没有结果后,我尝试使用 malloc 作为替代方案,我更大的工作所基于的原始代码是在 C 中,所以这里有一些东西需要修复。进行您建议的更改后,我再次遇到了分段错误。
  • 我想您的问题已经解决了,请将答案标记为已接受。 @A.Dakroury
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多