I am seeing some really weird behavior in my C project - https://github.com/ryu577/base/blob/master/numerical/c/NumericalRecipiesCode/src/ch05/tst5.c
On line 77, I run one of the routines on "testFn" which is on line 13 and I have also included below. I do this by passing a pointer to the function.
float testFn(float x)
{
return x*x;
}
Next, on line 87, I simply attempt to initialize a 1d array of floats based on a boilerplate routine from Numerical recipes in C:
float *c1; c1 = vector(0, n1);
The "vector" function is quite simple and included here:
float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
if (!v) nrerror("allocation failure in vector()");
return v-nl+NR_END;
}
Now, when I print the entries in my "vector" (float array - c1), this is what I get -
12.00 12.00 12.00 0.00 0.00
Somehow, it decides to put 12s in the first 3 positions. But what is really interesting is that these numbers depend on how I define testFn. For example, if I define it as:
float testFn(float x)
{
return x*x*x;
}
I then get the entries of c1:
112.00 110.04 109.04 108.53 0.00
But the thing is that the creation and initialization of the vector had nothing to do with testFn at all. So, how is it able to influence its values in this way? Is it related to some block of memory that isn't being freed up and the values are spilling over into the new array?