0

I'm working on a C program that needs a lot of dynamic memory allocation of 1-D and 2-D arrays.

The program works fine when I compile and run it using windows and Visual C++, but when I compile and run it in a Unix environment, I get slightly different results, and a message at the end of my results saying 'Segmentation fault'.

The programs are identical, so I don't know why I don't get the same results in both instances. I'm sure that it has something to do with the dynamic memory allocation.

Please help!

3
Contributors
5
Replies
7
Views
7 Years
Discussion Span
Last Post by Ancient Dragon
0

It's too long winded to put up all the code, but here's the main guts of it...
Again, I don't think there's a problem with the code. It works fine in windows. But there must be some unix command I'm leaving out. I'm not too hot with unix, but I've been adding the '-lm' tag so that it'll compile with the "math.h" header file.

/* dynamically declare array to store tiangular matrices */
lower_tri = (float **)malloc(sizeof(float *)*(dimention));
for(i =0; i < dimention; ++i)
	lower_tri[i] = (float *)malloc(sizeof(float)*(i+1));

/* initialise triangular matrix to zero */
for(i =0; i < dimention; ++i)
	for(j =0; j <= i+1; ++j)
		lower_tri[i][j] = 0;                                            

/* calculate the rest of lower triangular matrix */
for(j =0; j < dimention; ++j) {
	for(i =j; i < dimention; ++i) {
		/* find corresponding non zero value (if any) */
		for(k = xadj[j]; k < xadj[j+1]; ++k)
			if(adj[k] == i)
				lower_tri[i][j] = values[k];
		
for(k = j-1; k >= 0; --k)
			lower_tri[i][j] -= lower_tri[i][k]*lower_tri[j][k];

		if(i == j)	/* diagonal term */
			lower_tri[i][j] = (float)sqrt(lower_tri[i][j]);
		else		/* off diagonal term */
			lower_tri[i][j] /= lower_tri[j][j];
	}
}
0

If it works on MS-Windows its just by dump luck

>>line 17: lower_tri[j] = values[k];
Look at line 4 and tell me how many floats are allocated to each row of lower_tri array. Answer: Row #0 is 1 float, row #1 is 2 floats, row #3 is 3 floats etc. That means line 17 is writing beyond the boundries of the array.

0

You're correct about the way lower_tri is allocated, but I don't believe it's writing beyond the boundary.

It's writing down each column rather than across each row.

Line 12&13

for(j =0; j < dimention; ++j) {	
for(i =j; i < dimention; ++i)

Edited by evinkeating: n/a

0

What you have created is an array in the shape of a right triangle instead of a rectangle. Which is unusual, and now you have unused elements of the array. That may be what you intend, I don't know.

And yes, that isn't the answer to the problem. Use your debuger and fid out what is causing it.

Edited by Ancient Dragon: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.