I have an interesting behavior of my program. Its better to show code first.
typedef struct PS {
int num;
} PR;
typedef struct PS* PN;
typedef struct {
int num;
int tmp;
} VD;
void F (PN VPtr)
{
register VD* qVPtr = (VD*)VPtr;
// if this is call #2
// qVPtr->tmp already is 8 for VP arg
// qVPtr->tmp already is 16 for VP1 arg
switch(VPtr->num){
case 0:
qVPtr->tmp = 8;
return;
case 1:
qVPtr->tmp = 16;
return;
}
}
int main()
{
PN VP = NULL;
VP = (PN)malloc(sizeof(PR));
VP->num = 0;
F (VP);
PN VP1 = NULL;
VP1 = (PN)malloc(sizeof(PR));
VP1->num = 1;
F (VP1);
F (VP); // call #2 with VP arg
F (VP1); // call #2 with VP1 arg
return 0;
}
In main function VP and VP1 does not knows about qVPtr and tmp field, but depending on VPtr argument in F function it is possible to obtain last value of qVPtr->tmp.
Can you explain in detail about this possibility?
There is nothing strange in F behaviour – if you told it to consider pointer
VPtr as pointer to VD struct, it considers memory, starting with VPtr as memory containing VD struct object though there is no any VD object there. Your “magic” appears because both structs PR and VD start with integer field of the same size.
But next part of memory is unallocated that means system can do whatever it wants with it and when you write there you can shoot in your leg.