The problem is shown by the following code: basically, when using the +=
operator on a pointer which is the member of a class as in a line like below:  
         a.myptr += a.SideEffect();
if the a.myptr pointer is modified by the a.SideEffect() call, the += still
takes into account only the old pointer value to compute the += result. I was
expecting it to use the value modified by the a.SideEffect() call. See code
below to reproduce.

The behaviour I expected can be obtained if, in the code below, the class A is
removed and all variables/functions are changed to be global
variables/function.

Compiled under RHEL5, kernel 2.6.20-hardened-r2
gcc --version gives:
gcc (GCC) 4.1.2 20070626 (Red Hat 4.1.2-14)

---------- sample code -----------
#include <stdio.h>

class A{
public:
  int SideEffect(void){
        // prints that we are at position 0 in the buffer (correct)
        printf("position in buffer when entering SideEffect: %d\n",
myptr-buffer);
        myptr += 2;
        // prints that we are at position 2 in the buffer (correct)
        printf("position in buffer when leaving SideEffect: %d\n",
myptr-buffer);
        return 10;
  }
  char buffer[256];
  char * myptr;
};


int main(void){
  A a;
  a.myptr = a.buffer;
  a.myptr += a.SideEffect();
  // Likely bug: prints position 10, I was expecting 12
  printf("position in buffer after calling SideEffect and += operator, expected
value is 12: %d\n", a.myptr-a.buffer);
  return 0;
}


-- 
           Summary: += operator on pointers with a function call having side
                    effects on the right hand side
           Product: gcc
           Version: 4.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: daniel dot fredouille at gmail dot com


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34948

Reply via email to