Question

How does a program/application know that the data in a memory address is of a certain data type.

For instance, suppose there is int a; and suppose variable a is stored in address 0x100. Where is the the information stored that says it is of type int?

Was it helpful?

Solution

In languages like C the information is always "stored" in the way you interpret the data. Some niceness is added by the compiler which to some extent understands the types of your variables and tries to prevent operations which don't make sense.

For instance, suppose you have the bits: 0xFFFFFFFF. If you interpret them as "a 32b unsigned int" you'll get 4294967295. If you interpret them as "a 32b signed int" you'll get -1(*). If you interpret them as a double, god knows what you'll get.

OTHER TIPS

Nowhere, it's just assumed by the code.

A C application does not store type information. The only enforcement is with how the data is used. And, in C, it is a very simple matter to abuse that enforcement.

Consider the following:

short s;
short *p = &s;
*(long*)p = 0;

This code takes a pointer to a short variable, and then writes to that variable as though it were a long. This overwrites memory beyond what is owned by the variable being used, causing undefined behavior.

This information is not stored. For example, you could do things like

int i=15;
char *p=(char*)&i;
char c=*p; //Now, c contain the first byte of 15, which may be 15 or 0

But don't do this unless you really know what do you do. Do stuff like this uncarefully is a common way to errors.

When the C program is past linking, and don't need to expose any symbols outside, this data does not exist anymore.

The data types are language-related, when the executable is ready, the language don't play a part anymore, as now it's all memory and processor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top