1

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.

Kammeot
  • 469
  • 7
  • 18
  • 2
    VLAs are not yet a part of C++. – chris Jul 10 '13 at 17:19
  • I know, I create the poi array to be of the maximum size that it could possibly need to be, and then record the actual number of poi that are included in the poi array thus curtailing it. This might be bad practice, but still, the print statement shouldn't do anything to the output. – Kammeot Jul 10 '13 at 17:23
  • 4
    The line `return poi;` returns a pointer to a __local__ array. That is completely broken. See: [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Blastfurnace Jul 10 '13 at 17:26
  • damn, that breaks a lot of things. Well then, that's probably where my mysterious problems are arising. god I feel like a noob. @Blastfurnace if you formulate that into an answer, I'll accept it. -_- – Kammeot Jul 10 '13 at 17:33

1 Answers1

2

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.

Community
  • 1
  • 1
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70