For example, we have
int* p;
Could this pointer be initialized by 0 randomly, it means initialized by the operating system, in this case we dont change the value of this pointer ?
For example, we have
int* p;
Could this pointer be initialized by 0 randomly, it means initialized by the operating system, in this case we dont change the value of this pointer ?
Here's the tricky part: no valid program can figure this out. Reading p
is Undefined Behavior, and anything may happen including returning nullptr
even though p
doesn't actually contain nullptr
(!)
If you wonder how that's possible, p
may be put in a register on first write. Trying to read p
before that would give rather random results.
Assumption: you are talking about the possibility that the return of a malloc or new should happen to be 0 at some point.
In this case, I believe the answer is no. The pointer will take a virtual address. Being something allocated dynamically, it will get an address belonging to the Heap that will never start at address 0.
The virtual memory space of your process is divided in more sections: Text, Data, BSS, Heap (where all the dynamically allocated objects go), the stack and the kernel space. The image below is for a 32b OS but for 64b the picture is similar.
You can make a small program and read some addresses in different spaces, and understand what you can and cannot access.
The heap (the place where your pointer will point), grows after the Text, Data and BSS segments. So it will never be 0.
Declaring the variable as Global or static would be automatically initialized to 0X0 by OS.