Search code examples
c++windowscomplex-numbersgsl

gsl_complex causing memory overflow


I'm seeing some odd behaviour from the GNU Science Library complex number functions. The issue is demonstrated in the following snippet:

#include <iostream>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>

int main() {
    double realNumber = 1.0;
    gsl_complex complexNumber;

    GSL_SET_COMPLEX(&complexNumber, 1.0, 1.0);

    printf("%p: ", &realNumber);
    printf("%f\n", realNumber);

    gsl_complex_add(complexNumber,complexNumber);

    printf("%p: ", &realNumber);
    printf("%f\n", realNumber);

    return 0;
}

The output is

0061FF18: 1.000000
0061FF1C: 0.000000

The function gsl_complex_add changes the value of the pointer to realNumber such that it no longer points to realNumber, even though realNumber doesn't seemed to be linked to the function in any way. I assume this is due to some sort of overflow.

The problem does not occur if I use std::cout instead of printf; I imagine this is due to the compiler.

If I declare realNumber as static the problem does not occur.

If I declare realNumber as const, printf("%p: ", &realNumber); returns an incorrect value, but printf("%f\n", realNumber); returns the correct one.

Is this a bug or am I doing something I shouldn't be?

I am using the g++ compiler (version 6.3.0) on a Windows machine.

Thanks in advance for your help.


Solution

  • After further investigation I realised that I was using a very old version of GSL. The described behaviour disappeared after updating to the latest stable version.