Near and Far Heaps

As mentioned in the previous section, heap memory can reside inside or outside your program's default data segment, depending on what memory model your program uses. When it lies inside the default data segment, the heap is called the “near heap,” since it can be accessed with near pointers. The “far heap” is memory that spans one or more segments outside the default data segment. The far heap can be accessed only with far pointers.

In various memory models, malloc automatically allocates memory from the near heap or far heap, as appropriate. The run-time library also includes near and far versions of malloc, free, and other memory-management routines, which allow you to specify the near and far heaps explicitly. These have the same names as standard memory routines, but are preceded by _n (for near) or _f (for far).

For instance, the _nmalloc routine always allocates memory from the near heap and returns a near pointer, no matter which memory model your program uses. Use _nfree to release memory allocated with _nmalloc.

Similarly, _fmalloc always allocates memory from the far heap and returns a far pointer, regardless of memory model. Use the _ffree routine to release memory allocated with _fmalloc.