Why does the following code run?
#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;
}
The output is
num=5
I compile this using gcc and I get only the following compiler warning at line 10:
(warning: ‘a’ is used uninitialized in this function)
But as per my understanding, shouldn’t this code not run at all? And how come it’s assigning the value 5 to num when num doesn’t exist because no object of type A has been created yet?
You haven’t initialized
*a.Try this:
Not initializing pointers (properly) can lead to undefined behavior. If you’re lucky, your pointer points to a location in the heap which is up for initialization*. (Assuming no exception is thrown when you do this.) If you’re unlucky, you’ll overwrite a portion of the memory being used for other purposes. If you’re really unlucky, this will go unnoticed.
This is not safe code; a “hacker” could probably exploit it.
*Of course, even when you access that location, there’s no guarantee it won’t be “initialized” later.
“Lucky” (actually, being “lucky” makes it more difficult to debug your program):
“Unlucky” (makes it easier to debug your program, so I don’t consider it “unlucky”, really):