Why does it work? This is a small example, but he even worked on a much more complex project.

#include <cstdio>
class baseclass
{
};

class derclass : public baseclass
{
public:
    derclass(char* str)
    {
        mystr = str;
    }
    char* mystr;
};
baseclass* basec;

static void dostuff()
{
    basec = (baseclass*)&derclass("wtf");
}

int main()
{
    dostuff();
__asm // Added this after the answer found, it makes it fail
{
    push 1
    push 1
    push 1
    push 1
    push 1
    push 1
    push 1
    push 1
    push 1
    push 1
}
    printf("%s", ((derclass*)basec)->mystr);
}
+3
source share
6 answers

Ugh. This is one example of "never do this." In dostuffyou create a temporary type derclass, take its address and delete it outside dostuff(assigning it basec). As soon as the line creating the temporary one is finished, access to it through this pointer gives undefined behavior. The fact that it works (i.e. your program prints "wtf") certainly depends on the platform.

? , , ++. derclass. ? , . ( ) .

, , . , . - , (, , "wtf", - ), .

-, dostuff printf. , , factorial(10) . , printf .

+10
basec = (baseclass*)&derclass("wtf");

derclass , ; dostuff(). , basec .

+6

aJ, . "": undefined, , !

: undefined - .

+3

, basec = (baseclass*)&derclass("wtf"); undefined. , derclass("wtf") ( derclass), & , basec. , , , basec . ( (derclass*)basec)->mystr), undefined.

undefined , , , . , .

, basec, , . : basec = new derclass("wtf").

+2

, basec, - derclass, , .

: , . , ?

(baseclass*)?

+1

, dostuff(). dostuff , , , , . , , , printf, , .

, , , .

, , mystr. . .

- :

void breakStuff()
{
   char dummy[3];

   strcpy( dummy, "blahblahblahblahblah" );

   int i = 7;
   i = i + 8;
   i = i + 22;
   printf( "**%d**", i );
}

strcpy PAST . . , .

+1
source

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


All Articles