Pointer Arithmetic Wraps Around Segment Ends

Last reviewed: July 17, 1997
Article ID: Q58987
5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a 7.00 | 1.00 1.50 1.51
MS-DOS                      | OS/2                 | WINDOWS
kbprg

The information in this article applies to: The Microsoft C/C++ Compiler (CL.EXE), included with:

  • Microsoft C for MS-DOS, versions 5.1, 6.0, 6.0a, and 6.0ax
  • Microsoft C for OS/2, versions 5.1, 6.0, and 6.0a
  • Microsoft C/C++ for MS-DOS, version 7.0
  • Microsoft Visual C++ for Windows, versions 1.0, 1.5, and 1.51

SUMMARY

In Microsoft C and C++, when you increment or decrement a pointer beyond a segment boundary, the offset of the pointer will wrap around the end. For example, if the pointer is sitting at FFFF and you increment it by 1 (one), the resulting value of the offset is 0000. This wraparound behavior is expected behavior in all memory models except huge. The example below demonstrates the "hidden" wraparound.

MORE INFORMATION

The C language permits writing beyond array boundaries and heap allocations. Consequently, C compilers do not generate warning or error messages if an index or pointer goes out of bounds. It is up to the programmer to monitor indices and pointers.

If you have an array that is larger than 64K, use the huge keyword or compile in the huge memory model. Pointer arithmetic for huge data is performed on the full 32 bits of segment and offset address.

Sample Code

/* Compile options needed: none
*/

#include <stdio.h>
#include <dos.h>
#include <malloc.h>

void main (void)
{
 char *ptr;

 ptr = (char*) malloc (100);
 printf ("\nSegment is %u, offset is %u\n", FP_SEG(ptr), FP_OFF(ptr));

 FP_OFF(ptr) = 0x0000;
 printf ("\nSegment is %u, offset is %u\n", FP_SEG(ptr), FP_OFF(ptr));
 ptr--;
 printf ("\nSegment is %u, offset is %u\n", FP_SEG(ptr), FP_OFF(ptr));

 FP_OFF(ptr) = 0xFFFF;
 printf ("\nSegment is %u, offset is %u\n", FP_SEG(ptr), FP_OFF(ptr));
 ptr++;
 printf ("\nSegment is %u, offset is %u\n", FP_SEG(ptr), FP_OFF(ptr));
}


Additional reference words: kbinf 1.00 1.50 6.00 6.00a 6.00ax 7.00 8.00
8.00c
KBCategory: kbprg
KBSubcategory: CLngIss
Keywords : kb16bitonly


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: July 17, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.