Identifying an in-memory data type in C?
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.
source to share
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.
source to share
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.
source to share