[Solved]Problem of An Access Violation In A Easy Program

Hello everyone

I have programed a matrix with c++ and got "an access violation (segmentation fault) raised in your program" in the constructor. It is very strange because this problem only occurs, if the matrix is larger than 10*2. A 9*2 matrix works perfectly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Matrix::Matrix(int i, int j){
	int k=0;
	row=i;
	column=j;

	matrix=(double**) malloc(sizeof(double)*column);	
		for(int i=0;i<row;i++)
			matrix[i]=(double*)malloc(sizeof(double)*row);	

		do{
				for(j=0;j<column;j++)
	 	 			this->matrix[k][j]=0;
				k++;
		}
		while(k<row);
				
	}


Row and column are already decleared as int in header.
The error message is in line 12.

Who can help me to solve this problem, please??? Thanks!!!
Last edited on
Dangerous Error!!

Your program also crashes with 9*2 Matrizes, but with the size of the Matrix it becomes more probable.

Solution:
The reason is tricky. The mistake is in line 11. You mixed up the rows and the columns. Change line 12 to:
this->matrix[j][k]=0;
Normally matrix[a][b] means, a is the row, b the column, but you allocated memory the way, that a is the column and b the row (lines 6 and 8). This caused all the trouble.

Explanation:
In line 6 you allocate memory, the same for every column in line 8. The program tries to allocate the next memory - if possible. This is for performance reasons. In line 12 you are accessing this memory via a pointer k, which is increased in line 13. So, if your memory is in one block, your program runs perfectly, but if it's fragmented, it crashes. This is a really dangerous mistake, because maybe your program runs 9 out of 10 times without any error, but sometimes still crashes.

By the way:
You're allocating too much space in line 6. What you mean is sizeof(double *), not sizeof(double):
matrix=(double**) malloc(sizeof(double *)*column);
And instead of the for loop in lines 7&8 i would recommend:
1
2
3
matrix[0]=(double *)malloc(column*row*sizeof(double));
for(int i=1;i<row;i++)
     matrix[i]=matrix[0]+i*column;

This ensures, that your Memory is not fragmented. It can save you a lot of trouble
Last edited on
I'm going to suggest using new/delete instead of malloc/free also. As these are the C++ memory management methods.
it works now with new/delete.
thank u.
Topic archived. No new replies allowed.