Kammeot
Kammeot

Reputation: 469

Print statement changing output of function?

I have a bit of c++ code that's supposed to look at the derivative of a function and collect the points that have a slope greater than some threshold. It's been giving me troubles, so I've been putting print statements everywhere to figure out what is going wrong. I stumbled upon a baffling issue where when I used std::cout<< to print the size of an array, it changed the output of the function! Here's the code snippet:

int* Tools::findPoi(float* y, int size, float threshold, int width, float step, int* outsize){
int poi[size];
float* derive = derivative(smooth(y,size,width),size, step);
int n = 0;
std::cout<<size<<" data size\n";
for(int i = 0; i<size; i++) {
    if(derive[i] > threshold) {
        poi[n] = i;
        n++;
    }
}

*outsize = n-1;
return poi;
}

without the commented out line "std::count..." I get 82 poi. But if I comment it out or remove it I get 84 poi. Nothing else changes, only this print statement. I am so confused as to why or even how it could possibly change the output. Any help would be greatly appreciated.

EDIT: ok, so actually, it's just random. The variable n is different everytime I run it, which leads me to believe that something weird is going on in memory.

Upvotes: 1

Views: 1944

Answers (1)

Blastfurnace
Blastfurnace

Reputation: 18652

There is a significant problem with the line:

return poi;

This returns the address of a local object. The array no longer exists when it goes out of scope at the end of the function. For a wonderful explanation see: Can a local variable's memory be accessed outside its scope?.

Since this is C++ and you want a dynamic array I suggest you use std::vector. It solves many problems such as this.

Upvotes: 2

Related Questions