Daniel
Daniel

Reputation: 778

How and where is variable type information stored?

If I have allocated memory for an int, I will (usually) be given 4 bytes. As I understand, these 4 bytes make up the entire footprint of this variable in memory.

Furthermore, if I have a pointer to this int, it will hold the address of the first of its 4 bytes.

However, how does my program know that the type of data in those 4 bytes consists of a single int? And since my pointer only holds this address, which supposedly only holds raw data, how does it know that whenever the address it holds is dereferenced, it should be interpreted as an int?

Where is this type information, and how and when does the program access it?

Upvotes: 8

Views: 1676

Answers (1)

John Zwinck
John Zwinck

Reputation: 249223

Once you compile a C program, the type information is essentially lost (or put another way, it is no longer needed). This is because the interpretation of any bytes of memory in C are up to the code which reads them. You can read a four-byte int as a char[4] with no problems, for example.

Type information may be preserved in certain cases for special reasons, such as debugging. But this is stored in platform-specific formats (e.g. DWARF on Linux), and is not part of the C standard at all.

Upvotes: 14

Related Questions