Pointer Arithmetic Wraps Around Segment EndsLast reviewed: July 17, 1997Article 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 | WINDOWSkbprg The information in this article applies to: The Microsoft C/C++ Compiler (CL.EXE), included with:
SUMMARYIn 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 INFORMATIONThe 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
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |