C language pointer type detailed resolution

  • 2020-04-02 01:33:52
  • OfStack

Pointers store the address of memory, and Pointers are typed, such as int*,float*, so a natural guess is that pointer variables should store the two aspects of information: address and pointer type, for example, like the following structure:


struct pointer{
    long address;
    int type;
}

For example: print sizeof(int*) with a value of 4, so 4 bytes is used to store the memory address, which in turn means that the pointer does not have a place to store the type information.
Let's take a look at a simple piece of code.

//Ma.cpp: defines the entry point for the console application.
#include "stdafx.h"
char gi;
char *pi;
void main()
{ 
pi=&gi;
*pi=12;
}

Disassembly results:

pi=&gi;
0041137E C7 05 78 71 41 00 7C 71 41 00 mov         dword ptr [pi (417178h)],offset gi (41717Ch) 
*pi=12;
00411388 A1 78 71 41 00   mov         eax,dword ptr [pi (417178h)] 
0041138D C6 00 0C         mov         byte ptr [eax],0Ch 
}

So byte tells you about the pointer type.
Conclusion: C language pointer types include two aspects of information: one is the address, stored in pointer variables; The second is the type information, which is related to the length of read and write. It is not stored in the pointer variable, but in the mov instruction when reading and writing with the pointer. Different read and write lengths correspond to different mov instructions.

In addition: This is also the case with pointer casts. That is, the effect of pointer casting does not occur during the conversion, but is reflected in the instruction when the converted identity is used to access memory.

So when is a pointer conversion safe? To see if it is safe to access memory with this transformed identity. Briefly, there are the following Principle: If the converted pointer points to a data type smaller than the size of the original data type, then access with the converted pointer will not cross the original data memory, is safe, otherwise dangerous to cross the boundary.


Related articles: