Consecutive lines printing same pointer with "std::cout" produce completely different output

Advertisements

I apologize for the vague title of my question. I don’t know a better way to phrase it. I’ve never asked a Stack Overflow question before but this one has me completely stumped.

A method in class Chunk uses the Eigen linear algebra library to produce a vector3f, which is then mapped to a C-style array with the following.

ColPivHouseholderQR<MatrixXf> dec(f);
Vector3f x = dec.solve(b);

float *fit = x.data();
return fit;

This array is returned and accessed in the main function. However, whenever I attempt to print out a value from the pointer, I get completely different results. A sample is below.

Chunk test = Chunk(CHUNK_SIZE, 0, 0, 1, poBand);
float* fit = test.vector;  // Should have size 3
std::cout << fit[0] << std::endl; // Outputs 3.05 (correct)
std::cout << fit[0] << std::endl; // Outputs 5.395e-43
std::cout << fit[0] << std::endl; // Outputs 3.81993e+08

What makes this issue even more perplexing is that the incorrect values change when I end the lines with "\n" or ", ". The first value is always the expected value, no matter whether I print index 0, 1, or 2.

I have tried dynamically allocating memory for the fit variable, as well as implementing the code on this answer, but none of it changes this functionality.

Thank you in advance for any guidance on this issue.

Minimally Reproducible Example:

float* getVector() {
    Eigen::Vector3f x;
    x << 3, 5, 9;

    float* fit = x.data();
    return fit;
}

int main(void) {
    float* fit = getVector();

    std::cout << fit[0] << std::endl;
    std::cout << fit[0] << std::endl;
    std::cout << fit[0] << std::endl;
}

>Solution :

You create the vector x in the function on the stack. It is destroyed after the function exited. Hence your pointer is invalid.

Here an example with shared_ptr

ColPivHouseholderQR<MatrixXf> dec(f);
Vector3f x = dec.solve(b);
shared_ptr<float> fit(new float[3],std::default_delete<float[]>());
memcpy(fit,x.data(),sizeof(float)*3);
return fit;

Another possible way is

ColPivHouseholderQR<MatrixXf> dec(f);
Vector3f x = dec.solve(b);
return x;

Leave a ReplyCancel reply