-1

I want to ask question bout double *S () this function.

It's will wrong in Online Judge, But both work on VS or Dev, I don't know why.

#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<iostream>
#include<cmath>

using namespace std;

class F {
private:
    double a,r;
public:
    F(double x, double y) {
    a = x;
    r = y;
    }
  
    double at (int x) {
        return a * pow(r, x); 
    }
  
    double *S () {
      if (r >= 1 || r<= -1) 
        return nullptr;
        double* x;
        double b= double(a / (1 - r));
        x = &b;
        return x;
}


};

int main()
{
    int j, k;
    double a, r;
    cin>>a>>r;
    F f(a, r);
    for(k = 0;k < 3;k ++)
        printf("%.2lf\n", f.at(k));
    double *s = f.S();
    if(s == NULL)
      printf("NULL\n");
  else
    printf("%.2lf\n", *s);
}
    double *S () {
      if (r >= 1 || r<= -1) 
        return nullptr;
      double* z= new double(a / (1 - r));
        return z;
}

It's will AC on OJ.

    double *S () {
      if (r >= 1 || r<= -1) 
        return nullptr;
        double* x;
        double b= double(a / (1 - r));
        x = &b;
        return x;
}

It's wrong on Oj.

yunung
  • 1
  • 3
  • You are returning the address of a local variable. That no longer really exists once the function has returned and attempting to access it is undefined behaviour. – Adrian Mole May 04 '22 at 12:18

1 Answers1

1
double b= double(a / (1 - r));

This variable has automatic storage duration. The lifetime of b will end when the execution reaches the end of the scope where b is declared, which is when the function returns.

x = &b;
return x;

x points to the automatic variable whose lifetime has ended when the function returns. The returned pointer will be invalid. When you attempt to access the destroyed object through this invalid pointer at *s, the behaviour of the program is undefined.

eerorika
  • 232,697
  • 12
  • 197
  • 326