PRB:Compiler May Not Account for Side Effect on Global Pointer

ID Number: Q67786

6.00 6.00a 6.00ax | 6.00 6.00a

MS-DOS | OS/2

buglist6.00 buglist6.00a buglist6.00ax fixlist7.00

Summary:

SYMPTOMS

The Microsoft C Compiler versions 6.0, 6.0a, and 6.0ax produce

incorrect code when the sample program below is compiled with any

optimization other than /Od. The code generated by the compiler

incorrectly assumes that ptr1 and ptr2 are equal after the call to

the function inc_ptr1. The compiler then accesses ptr2[1] by using

the value of ptr1 rather than the value of ptr2. This generates the

wrong effect on the array being modified.

RESOLUTION

There are several workarounds to this problem:

1. Use the /Od option to disable optimization.

-or-

2. Compile with the /qc (quick compile) option.

-or-

3. Declare ptr1 as a volatile pointer to a char.

-or-

4. Change the code to assign buf to ptr2 first.

STATUS

Microsoft has confirmed this to be a problem in C versions 6.0,

6.0a, and 6.0ax. This problem was corrected in C/C++ version 7.0.

More Information:

Sample Code

-----------

/* Compile options needed: none

*/

#include <stdio.h>

char inc_ptr1 (void);

char * ptr1;

char * ptr2;

char * buf = "....................";

main ()

{

ptr1= buf;

ptr2= buf;

ptr2[1]= inc_ptr1 ();

printf ("buf = %s\n", buf);

printf ("ptr1 = %d\nptr2 = %d\n", ptr1, ptr2);

}

char inc_ptr1 ()

{

ptr1 += 10;

return (char) '[';

}

The correct output is:

buf = .[..................

ptr1 = 76

ptr2 = 66

The output generated is:

buf = ...........[........

ptr1 = 76

ptr2 = 66