Re: dangling reference

From: Method Man (a_at_b.c)
Date: 10/15/04


Date: Thu, 14 Oct 2004 18:47:04 -0400


"Hans Van den Eynden" <onsbomma@hotmail.com> wrote in message
news:1c2f5137.0410141238.4cb7a4ab@posting.google.com...
> I thought that integers resized on the stack and that a value type was
> just defined in the scope of the function. And when the function
> returns the local variables were removed from the stack. But what is
> the explication of this code??
>
> int& dangling_reference();
>
> int main(int argc, char *argv[])
> {
> int a;
> a= dangling_reference();
> cout<<a<<endl;
> cin.get();
> }
>
>
>
> int& dangling_reference() {
> int x=3;
> return x;
> }

This is UB. If you are getting the correct result (printing "3"), then
you're just lucky. This probably occured because your program is small and
the contents of the memory address of 'x' are still intact. Regardless, you
should not *expect* your code to work.



Relevant Pages

  • Re: EcmaScript 4
    ... stack. ... // definition in local stack scope ... - a dummy callback function is defined on the object's prototype. ... in a subsystem while the solution logic that responded to user actions ...
    (comp.object)
  • Re: EcmaScript 4
    ... stack. ... // definition in local stack scope ... A major goal of OOA/D is to define behaviors in exactly that sort of self-contained fashion where they only depend on the current state of the solution represented by message data and the current values of relevant state variables. ... a dummy callback function is defined on the object's prototype. ...
    (comp.object)
  • Re: EcmaScript 4
    ... structuring, and stack-based scope. ... stack. ... a dummy callback function is defined on the object's prototype. ... objects; and objects collect responsibilities. ...
    (comp.object)
  • Re: How does managed code work?
    ... Does it work the same way as the native stack with a frame pointer that is the head of a linked list of stack frames where each time we enter a function we create a new stack frame in which new variables are pushed and each time we exit a function the entire stack frame is popped? ... Can someone point me to a discussion of the managed heap? ... How does it prevent memory leaks that occur in COM when two objects reference each other and keep the others reference count nonzero? ... Because objects don't go out of scope, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Lexical scope question
    ... from anywhere can be made to it ("indefinite scope"). ... You can imagine it being implemented in some kind of stack; ... the variable allows stack-like updates (they might be put on the stack ... data on as an argument to inner, ...
    (comp.lang.lisp)