A. Dakroury A. Dakroury - 10 days ago 7
C++ Question

Segmentation fault (core dumped) if I don't include a cout?

I was working on creating a dynamic array based on an input file and was being thrown a Segmentation fault error with no useful information with gdc.
Whilst debugging I tried checking if Ntot was being read correctly and somehow that fixed the error.
If I remove the cout (as in the example) then the error returns, anyone got some insight why?

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

}


Edit: working array initialization is:

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

Answer

Start allocating memory from index 0 onwards, since indexing in C/C++ is from 0 and not 1.

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

Also, replace i by i - 1 in all number[i][j] above. Like number[1][1] = 1. by number[0][1] = 1. and so on.

And also, don't use malloc (and don't type-cast its result too !), instead use new :

number[i] = new double[Ntot];