'Why is a FILE* pointer zero-initialized in C++'s default initialization?
Consider
#include <iostream>
#include <cstdio>
using namespace std;
struct Foo {
FILE* fp;
Foo* mp;
};
int main()
{
Foo f1; // default initialization
cout << f1.fp << '\t' << f1.mp << '\n';
Foo f2{}; // zero initialization / direct-list-initialization
//Foo f2 = {}; // zero initialization / copy-list-initialization
cout << f2.fp << '\t' << f2.mp << '\n';
FILE* fp; // local POD variable, undefined
cout << fp << '\n';
}
Compilation and execution,
g++ tp.cc && ./a.out
gives something like:
0 0x5639eb8f00c0
0 0
0x5639eb8f02f0
Both FILE* fp and Foo* mp are of pointer types, thus also of POD types. So, in the default initialization (line Foo f1;), both should be not initialized. But the result, however, appears to suggest the FILE* fp is zero-initialized. How come? Is FILE* a special pointer type that the compiler loves to (zero) initialize, but refuses to zero initialize other pointers?
Solution 1:[1]
You didn't initialize the pointers. They get random (undefined) values (specifically, whatever the runtime happened to leave on the stack during initialization before main was called). Sometimes those values happen to be NULL. C++ didn't initialize them, you just got "lucky". As noted in the comments on your question, on different compilers, or with different variable declaration orders, the FILE* often ends up non-NULL, because it's not being initialized, just inheriting whatever happened to already be on the stack.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ShadowRanger |
