Sharat Chandra
Sharat Chandra

Reputation: 4554

Identifying data type of a value in memory in C?

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?

Upvotes: 3

Views: 1162

Answers (5)

Jonathan Wood
Jonathan Wood

Reputation: 67355

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.

Upvotes: 3

cnicutar
cnicutar

Reputation: 182774

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.

Upvotes: 12

asaelr
asaelr

Reputation: 5456

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.

Upvotes: 2

MByD
MByD

Reputation: 137442

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.

Upvotes: 1

heinrich5991
heinrich5991

Reputation: 2983

Nowhere, it's just assumed by the code.

Upvotes: 6

Related Questions