This is my first time posting a question to the forum, by the way.
I’m having problems implementing an algorithm, and I’ve narrowed it down to the following lines of code:
int Jacobi( double** A, double* b, int n, double* x0,
double tol, int maxInt ) {
int i = 0;
int j = 0;
int done = 0;
int loopCount = 0;
/*previous x variable*/
double* xPrev = 0;
/*update information*/
double** T = 0;
double* c = 0;
/*initialize x previous to a very large value*/
--->xPrev = ( double* )malloc( sizeof( double ) * n );
for( i = 0; i < n; i++ ) {
xPrev[ i ] = 5000.0;
}
...
}
By inspection via gdb, I have found that the line with the arrow pointing to it is the one that is causing the trouble. Before that line is executed, x0[ 1 ] = 1. Afterwards, it is somehow changed to x0[ 1 ] = (an extremely small number that I think is the minimum double precision value). I can’t figure out why this is happening, or how it is possible. Does anyone have any insight?
Here is the gdb run to prove it:
(gdb) break 88
Breakpoint 1 at 0x804881f: file linsys.c, line 88.
(gdb) run
Starting program: /home/stu1/s11/gaw9451/Courses/AP/hw4/linsys_test
Breakpoint 1, Jacobi (A=0x804b008, b=0x804b048, n=2, x0=0x804b060,
tol=9.9999999999999998e-13, maxInt=8) at linsys.c:88
88 xPrev = ( double* )malloc( sizeof( double ) * n );
(gdb) display x0[ 1 ]
1: x0[ 1 ] = 1
(gdb) next
89 for( i = 0; i < n; i++ ) {
1: x0[ 1 ] = 5.3049894774131808e-313
On a possibly related note, I get an error at run time when I free the variable xPrev at the end of the function. I had to comment it out to see any output from my program.
Summary: Does anyone have any idea how malloc can edit data in a completely different variable field?
Thanks in advance,
phoenixheart6
I am pretty sure you messed up a previous
malloc, something like allocating less than needed and nowmallocoverwrites what never belonged to you.Picture the
mallocmemory like this.Xregion represents what you asked frommalloc!region represents what you wrote past the legal size?region represents unused memoryNow when you do a second
malloc, it will feel perfectly entitled to give away “your”!part.