[comp.lang.c++] A bug in inline functions

eppstein@garfield (David Eppstein) (11/02/88)

This is in	#ident	"@(#)cfront:CC	1.11".

The problem: CC neglects to rename the arguments of an inline method,
creating a possible collision with global variables changed in the method.

The following example illustrates this.  The function x->pop() changes a
global variable s, then references x->val.  If called as s->pop(),
the generated code incorrectly references s->val for the new value of s
(which may be zero giving strange results) rather than the old value
(which should still be pointed to by this).  If I make the method
non-inline, it works correctly.

	Correct output		Output with inline bug
	2			1
	1			0
	0			1125191424

            ------------
#include <stream.h>

class stack * s = 0;

class stack {
    int val;
    stack * next;

 public:
    stack(int v) { val = v; next = s; }
    void pop() {
	s = s->next;		// change stack top
	cout << val << "\n";	// print value of THIS (not stack top)
    }
};

main()
{
    s = new stack(0);
    s = new stack(1);
    s = new stack(2);
    s->pop();
    s->pop();
    s->pop();
}
-- 
David Eppstein  eppstein@garfield.cs.columbia.edu  Columbia U. Computer Science