0

I have a function in my class like:

centrala* siec_telek::wylosuj_centrale()
{
    int wylosowana = dowolna_liczba_do(ilosc_central);
    centrala wylosowana_centrala = lista_central[wylosowana];
    centrala* wsk = &wylosowana_centrala;
    cout <<wsk->przepustowosc_central[0]<<endl<<wsk<<endl;
    return wsk;
}

And cout gives me good result but when I call in other function:

centrala* wylosowana_centrala = wylosuj_centrale();
cout << wylosowana_centrala->przepustowosc_central[0]<<endl<<wylosowana_centrala<<endl;

przepustowosc_central[0] gives another result but the pointer is ok (for instance 0x28f9cc twice)

  • 3
    You're returning a pointer to a local variable... The variable is long destroyed when you get out of the method. – jsantander Jun 10 '14 at 13:08
  • [undefined behaviour](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – chris Jun 10 '14 at 13:11

1 Answers1

0

Its because you are assigning local value address (wylosowana_centrala) to return value. Due to wylosowana_centrala being stored on stack it may got overwritten after exiting function.

As fix you might try changing

centrala* wsk = &wylosowana_centrala;

to:

centrala* wsk = &lista_central[wylosowana];
Łukasz Daniluk
  • 460
  • 3
  • 9