Explicit Address Manipulation in C ++

Please check out the following func function and its output

void main()
{
    Distance d1;
    d1.setFeet(256);
    d1.setInches(2.2);

    char *p=(char *)&d1;
    *p=1;

    cout<< d1.getFeet()<< " "<< d1.getInches()<< endl;
}

The class Distancegets its values ​​through setFeetand setInches, passing the arguments intand , respectively float. It displays values ​​through getFeetand methods getInches.

However, the output of this function 257 2.2. Why am I getting these values?

+3
source share
7 answers

This is a really bad idea:

char *p=(char *)&d1;
*p=1;

Your code should never make assumptions about the internal structure of a class. If your class had any virtual functions, for example, this code will fail when it is called.

, Distance :

class Distance {
    short feet;
    float inches;
public:
    void setFeet(...
};

setFeet(256), (MSB) 1 (256 = 1 * 2 ^ 8), (LSB) - 0. 1 char Distance, short, , 1. , short , 1, 1 * 2^8 + 1 = 257.

256, , 1 , 1.

, undefined, , . comp.lang.c , undefined ".

+14

"p".

undefined; , , .

:

struct Dist
{
    int     x;
    float   y;
};

union Plop
{
    Dist    s;  // Your class
    char    p;  // The type you are pretending to use via 'p'
};

int main()
{
    Plop    p;

    p.s.x   = 5;    // Set up the Dist structure.
    p.s.y   = 2.3;

    p.p     = 1;    // The value of s is now undefined.
                    // As you have scribbled over the memory used by s.
}
+2

, , . d1 clobber vptr, , / LSB MSB , Distance.

+1

, , * p = 1 ( "" ) "". , (afaik) , , ( char) .

, "" :

d1.feet = 1;
0

, : void main(). , . , C ++, .

++ 3.6.1 , main() int, .

, . , void main(), . , .

0

, .

, , SO .

.

0

class Distance{
    int feet;
    float inches;
    public:
//...functions
};

now int feet will be 00000001 00000000 (2 bytes), where zeros occupy a lower address in Little Endian, so char * p will be 00000000 .. when u make * p = 1, the low byte will become 00000001 so the int variable is now 00000001 00000001, which is exactly 257!

0
source

Source: https://habr.com/ru/post/1722015/


All Articles