C ++ function called without object initialization

Why is the following code executed?

#include <iostream>
class A {
    int num;
    public:
        void foo(){ num=5; std::cout<< "num="; std::cout<<num;}
};

int main() {
    A* a;
    a->foo();
    return 0;
}

Output signal

num=5

I compile this with gcc, and I get only the following compiler warning on line 10:

( warning: 'a' is used uninitialized in this function )

But, in my understanding, should this code not run at all? And how does it assign a value from 5 to num when num does not exist, since an object of type A has not yet been created?

+5
source share
7 answers

You did not initialize *a.

Try the following:

#include <iostream>

class A
{
    int num;
    public:
        void foo(){ std::cout<< "num="; num=5; std::cout<<num;}
};

int main()
{
    A* a = new A();
    a->foo();
    return 0;
}

() undefined. , , *. (, .) , , . , .

; "" .

* , , , "" .


"Lucky" ( "" ):

// uninitialized memory 0x00000042 to 0x0000004B
A* a;
// a = 0x00000042;
*a = "lalalalala";
// "Nothing" happens

"Unlucky" ( , "" ):

void* a;
// a = &main;
*a = "lalalalala";
// Not good. *Might* cause a crash.
// Perhaps someone can tell me exactly what'll happen?
+2

undefined, . undefined . , - - , .

, ? . undefined .

, 5 ? . undefined .

, 5? . 5. . undefined. , - 5 , .

+4

A* a; - .

, , , , .

.

.

, .

A* a(0); . .

.

+2
A* a;
a->foo();

undefined. .

§4.1/1 ++ 03 :

(3.10) , T r. T - , , . , lvalue T T, , , , undefined . T non-class, rvalue cv- T. rvalue .

: , -, ++- , undefined ?


5 num, num , A .

. .

+1

, .

a->foo(); , A::foo(a).

a - , . foo() a, , foo() a 4 5. .

? , , .

#include<iostream>
class A {
    int num;
    public:
        void foo(){ num=5; std::cout<< "num="; std::cout<<num;}
};

int main() {

    A* a;
    std::cout<<"sizeof A is "<<sizeof(A*)<<std::endl;
    std::cout<<"sizeof int is "<<sizeof(int)<<std::endl;
    int buffer=44;
    std::cout<<"buffer is "<<buffer<<std::endl;
    a=(A*)&buffer;

    a->foo();
    std::cout<<"\nbuffer is "<<buffer<<std::endl;
    return 0;
}
+1

, new, . , num, GCC , .

0

(-) : Tiny crashing program

envs , envs main.

Since it envsis an array of arrays (strings), it stands out very much, and you rewrite the first pointer in this list with 5, and then read it again for printing with cout.

Now this is the answer to why this is happening. You should clearly not rely on this.

0
source

All Articles