A. Dakroury A. Dakroury - 1 year ago 58
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;

//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.;
number[2][1] = 2.;
number[3][1] = 3.;
number[4][1] = 4.;
number[5][1] = 5.;

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 Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download