Reputation: 17
I'm trying to implement the ran2() method from Numerical Recipes. I found an implementation [here] 1 that I'm trying to get working.
I'm first trying to use the ran2_get_double(void* vstate)
function working but I've never used void pointers as a parameter before and I don't know how it works even if I have experience with pointers/references.
This is what I have so far in my main (cpp) file after a bit of trial and error:
double y{ 1.0 };
for (int i{ 0 }; i < 100; i++) {
double* z{ &y };
random_numbers.push_back(ran2_get_double(z));
}
This part of the code works, I get a series of random numbers, but at the end I get the error message:
Stack around the variable 'y' was corrupted.
I've looked around a bit and I suspect this has to do with memory management of the pointer but I'm really not sure where the issue is exactly. Can anyone spot the issue or suggest the best way to use the ran2() implementation here with its void parameter functions? Thanks
Upvotes: 0
Views: 192
Reputation: 12342
The ran2_get_double()
function takes a ran2_state_t
in form of a void *
as argument but you are passing a pointer to a double. This then causes a buffer overflow that corrupts your memory.
You need to create a ran2_state_t object and initialize it using ran2_set.
The functions should really just take a ran2_state_t *
as argument so errors like this don't happen. Or in the c++ world a ran2_state_t&
. Even better make it an object that retains it's own state and ran2_set becomes the constructor.
Upvotes: 2