segmentation fault, but no compiler error. simple program

Hi,
I have a very simple program that reads
a file line by line and stores each line in a 2-d array.
The program complies without error and runs correctly
when I use a small test file (that it reads from),
but when I use a larger file (has 300,000 lines instead of 2,000)
the program says segmentation fault when I run the executable.
It still compiles without error though.

How can this happen, if the only difference is the number of rows in the files.
Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <fstream>
#include <string>
/** 
The first line of the file being read contains two numbers, 
the number of rows and the number of columns, 
of a matrix that appears in the subsequent lines. 
The program stores the matrix as a 2-d array 
called "arr", and then prints the array to the screen. 
The file contains e.g.,
 2 3
 2.1 7 12
 8 3 0.1     
 
 **/


using namespace std;

int main()
{
   
    ifstream file("check.txt");
      
    if(!file.is_open())
    {
        cout << "Error opening file." << endl;
        return -1;
    }

    int numRows, numCols;
    file >> numRows >> numCols;

    double arr[numRows][numCols];

    // read each value into the array
    for(int i = 0; i < numRows; i++)
    {
        for(int j = 0; j < numCols; j++)
        {
            file >> arr[i][j];
        }
    }

    file.close();

    
    for( int i = 0; i < numRows; i++ )
    {
	for( int j = 0; j < numCols; j++ )
	{
	  cout << arr[i][j] << " ";	  
	}
	
	cout << endl;
    }
Last edited on
Also, I'm using g++ 4.7 and Ubuntu linux.
> The program complies without error
After adding the missing brace in line 57
$ g++ foo.cpp -pedantic-errors
foo.cpp: In function ‘int main()’:
foo.cpp:34:29: error: ISO C++ forbids variable length array ‘arr’ [-Wvla]
foo.cpp:34:29: error: ISO C++ forbids variable length array ‘arr’ [-Wvla]


I think that you are having an stack overflow.
You could allocate the array dynamically http://www.cplusplus.com/doc/tutorial/dynamic/
Last edited on
Topic archived. No new replies allowed.