Different values at same index double*

Hi,

So I have a function that amongst other arguments takes in an argument double* X.
The function behaves so that X is not mutated, its values are simply used for calculations.

However I have observed this weird behaviour where when I print I get different values of the same index of X, example:

1
2
3
4
5
6
7
8
9
10
11
12
13
fprintf(stderr,"1. X: %f %f %f %f\n",X[0],X[1],X[2],X[3]);

double ts=0;
for(int i=0;i<nInd4;i++){
   double tmp = ((r[i] = Y[i]-T[i]));
   if(X!=NULL){
       ts += tmp*tmp*X[i];
     } else{
       ts += tmp*tmp;
     }
}
// now X is different...
fprintf(stderr,"2. X: %f %f %f %f\n",X[0],X[1],X[2],X[3]);


So I know this probably is a bit hard with only a snippet of code, but is there any way the values of a pointer can be changed inside a function like this? I guess I am just asking for suggestions of possibilities.

I have even tried making X a const double* in the function, but this still happens...

I hope someone can help me!
Last edited on
It could happen if r points to the same array as X.

It could also happen if you loop out of bounds. Do the arrays have at least nInd4 elements?
Last edited on
Yeah, you need to show how it's called, what r is (where it's defined, what is it's size), and the value of nInd4. I suspect it isn't looping and writing out of bounds since that would overwrite the X pointer itself which should give pretty wacky results, most likely a segfault.
Last edited on
When I removed "r" the problem disappeared.

"r" was created as an array of doubles, and then the pointer to this array was passed on to the function, so that it had the type double* in the function arguments.

I do not think "r" had the right number of values... (this is some code I have adopted)

Do you have an explanation of what went wrong?

And thanks a lot for the feedback, much appreciated!
r would have to have been allocated with "new" if you wanted to pass it out of the function, otherwise r will be deallocated when the function returns, leaving your out pointer dangling.
Do you have an explanation of what went wrong?

If both r and x were created as arrays on the stack in the caller and then passed into the function, then writing past the end of r could write into x and change its values.
Topic archived. No new replies allowed.