0

I have the following code:

typedef void* EstimatedValue;

EstimatedValue myFunction()
{
    int myVal = 16;
    EstimatedValue value = &myVal ;
    return value;
}
bool intLessOrEqual(EstimatedValue value1, EstimatedValue value2)
{
    return *(int*)value1 <= *(int*)value2;
}

And this main function:

int x = 8;
EstimatedValue val = myFunction();
EstimatedValue x1 = &x;
intLessOrEqual(x1, val);

However, the value of the second argument (the one that is created in the function) is corrupt inside the intLessOrEqual function (the value is -858993460). If I try to access *(int*)val inside the main function it works ok. What could be the reason for this behavior? What can be done in order to avoid this behavior

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Nave Tseva
  • 371
  • 2
  • 6
  • 16

2 Answers2

1

myVal is created on the stack in the myFunction function. And you are returning an address to it. This leads to undefined behaviour because the value of myVal can change once it goes out of scope.

What you can do is create memory for value like this:

EstimatedValue value = malloc(sizeof(int);

Assign the value:

*value = 16;
return value;

In main after all the processing, you have to free that memory like this:

  free(val);
P.W
  • 26,289
  • 6
  • 39
  • 76
1

The problem is here:

EstimatedValue myFunction()
{
    int myVal = 16;                  // local variable
    EstimatedValue value = &myVal ;
    return value;                    // now release where myVal was
}

By the time this function have returned back to its caller, the memory where the local variable myVal is saved will have been released, and val in EstimatedValue val = myFunction(); essentially is pointing a memory space that is not occupied, i.e. anything else can be overwritten on it. Then what happens next is unpredictable.

fractals
  • 816
  • 8
  • 23