Microsoft KB Archive/58987

From BetaArchive Wiki

Pointer Arithmetic Wraps Around Segment Ends


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 #include #include 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
Issue type :
Technology : kbVCsearch kbAudDeveloper kbCVCComp

Last Reviewed: May 5, 2001
© 2001 Microsoft Corporation. All rights reserved. Terms of Use.