Borland Online And The Cobb Group Present:


June, 1994 - Vol. 1 No. 6

Calculating the environment block's size

In the accompanying article, Programming in DOS - Adding a DOS environment variable from inside a program we show you how to use a class to manage a DOS environment block's structure and content. However, since a user can change the amount of memory that DOS allocates for its environment block, the EnvBlock class needs to be able to find out how much memory the current block uses.

For every region of memory, or block, that DOS allocates for itself or for another process (free space, programs, device drivers, TSRs, and so on), it adds a 16-byte structure to the beginning of that block. DOS refers to this 16-byte structure as a Memory Control Block (MCB).

Each MCB contains information that DOS uses to manage the available memory for the PC. Bytes 4 and 5 of each MCB (offset 3 and 4) contain an unsigned integer that specifies the size of that particular memory block in paragraphs (16-byte chunks). Figure A shows how the MCB appears in front of the DOS environment block.


Figure A - Each block of DOS memory has a corresponding MCB.

DOS uses this information to determine where the next block of memory begins. In the EnvBlock class, we'll use this information to keep from writing environment block data past the end of the memory that DOS allocated for environment variables.

As Figure A shows, when we calculate a pointer to a DOS structure like the DOS environment block, the pointer points to the beginning of the actual data. It doesn't point to the MCB that precedes the data.

To retrieve the block size information from inside the MCB, you'll need to create a pointer that points 13 bytes below the data pointer (16 - 3 = first byte of size data). To get the value of the unsigned integer in this location, you can cast the pointer as an unsigned integer pointer and then dereference it, as follows:

blockSize = *((unsigned int*)sizePtr);

Once you know the size of the block in paragraphs, you can calculate the size in bytes by multiplying the paragraph size by 16.

Return to the Borland C++ Developer's Journal index

Subscribe to the Borland C++ Developer's Journal


Copyright (c) 1996 The Cobb Group, a division of Ziff-Davis Publishing Company. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff-Davis Publishing Company is prohibited. The Cobb Group and The Cobb Group logo are trademarks of Ziff-Davis Publishing Company.