Identifying an in-memory data type in C?

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

For example, suppose it exists int a;

and assume that the variable a

is stored in an address 0x100

. Where is the information specified in the type stored int

?

+3


source to share


5 answers


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



For example, suppose that you have a bit: 0xFFFFFFFF

. If you interpret them as "32b unsigned int" you get 4294967295

. If you interpret them as "32b signed int" you get -1

(*) . If you interpret them as double, god knows what you get.

+12


source


Nowhere, it's just assumed by the code.



+6


source


Appendix C does not store type information. The only use is data usage. And, in C, it is very easy to abuse this performance.

Consider the following:

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

      

This code takes a pointer to a short variable, and then writes that variable as if it were long. This overwrites memory outside of what's owned by the variable being used, causing undefined behavior.

+3


source


This information is not saved. For example, you can 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 you are doing. Doing things like this unnoticed is a common mistake.

+2


source


When a C program goes through a link and no characters need to be exposed outside, this data no longer exists.

The datatypes are associated with the language, when the executable is ready, the language no longer reproduces the part, as it is now all memory and processor.

+1


source







All Articles