tags:

views:

76

answers:

2

Hi,

I'm having problem getting the value from a pointer. I have the following code in C++:

void* Nodo::readArray(VarHash& var, string varName, int posicion, float& d)  
{  
    //some code before...
    void* res;  
    float num = bit.getFloatFromArray(arregloTemp); //THIS FUNCTION RETURN A FLOAT AND IT'S OK  
    cout << "NUMBER " << num << endl;            
    d = num;  
    res = &num;  
    return res  
}  

int main()  
{  
    float d = 0.0;  
    void* res = n.readArray(v, "c", 0, d); //THE VALUES OF THE ARRAY ARE: {65.5, 66.5};   
    float* car3 = (float*)res;  
    cout << "RESULT_READARRAY " << *car3 << endl;  
    cout << "FLOAT REFERENCE: " << d << endl;  
}  

The result of running this code is the following:

NUMBER 65.5 RESULT_READARRAY -1.2001
//INCORRECT IT SHOULD BE LIKE NUMBER
FLOAT REFERENCE: 65.5 //CORRECT

NUMBER 66.5 RESULT_READARRAY -1.2001
//INCORRECT IT SHOULD BE LIKE NUMBER
FLOAT REFERENCE: 66.5 //CORRECT

For some reason, when I get the value of the pointer returned by the function called readArray is incorrect. I'm passing a float variable(d) as a reference in the same function just to verify that the value is ok, and as you can see, THE FLOAT REFERENCE matches the NUMBER. If I declare the variable num(read array) as a static float, the first RESULT_READARRAY will be 65.5, that is correct, however, the next value will be the same instead of 66.5. Let me show you the result of running the code using static float variable:

NUMBER 65.5 RESULT_READARRAY 65.5
//PERFECT FLOAT REFERENCE: 65.5
//¨PERFECT

NUMBER 65.5 //THIS IS INCORRECT, IT
SHOULD BE 66.5 RESULT_READARRAY 65.5
FLOAT REFERENCE: 65.5

Do you know how can I get the correct value returned by the function called readArray()?

+4  A: 

You're returning a pointer to a stack variable (a local variable), which is no longer valid once you leave that function. It's called a dangling pointer.

One workaround would be to use

float *num = new float(bit.getFloatFromArray(arregloTemp); 
// ...
return (void*)num;

which would force num to be allocated on the heap, allowing the pointer to be used after the function exits.

But the better option, for the example above, would be to just have readArray return a float and return the value of num. You don't seem to gain anything by returning a pointer here.

Mark Rushakoff
+1 Great workaround, that is what I was looking for :DThanks Mark
Eric
+1  A: 

The num variable was declared inside scope, on the stack. Once the function has returned that memory location is no longer available, and although you most likely will be able to access it, it (usually) will not hold the value you need. In any case this is a bug.

To fix this you can either:

  • dynamically allocate that memory, and release it later on
  • return the value itself, and not a pointer
Yuval A
+1 for mentioning "return the value itself". It seems to be a natural approach in this case.
a1ex07