You are right in everything you say and in all your comments.
int *num = new int;
That, certainly, creates a int
. Neither more nor less than 1 and only 1 int
.
So, the big question is ... why does it work?
This is going to extend a bit. Let's see if with an image ( taken from here ) ...
Each time you make function calls, the arguments are placed on the stack ( stack ). You have it at the top of the image.
The data created with new
is occupying memory in the zone marked heap .
But all of it , from the part marked as .text
to the last byte of stack
belongs to your program . The system controls certain things, such as writings in read-only zones. But, for the rest, it's yours .
That means that, in fact, you can read and write in all your memory; another thing is that what you find have correct values.
The mechanism of dynamic memory reserve what it does is to organize some internal structures, so that you do not trample your own data; it guarantees that you will use different memory addresses for different things.
Initialization, on the other hand, is the mechanism by which you assign known initial values to variables.
But all of that are extra things , facilities we get from the system, from libraries, ... access to raw memory, skipping any logical organization > our , is always allowed.
That's why your code works. You read and write in your memory ; that you trample code structures (yours or from libraries), that you read initialized values or not ... that's the programmer's problem.
That is the great advantage and the big problem of C and C ++. They allow you to use completely the memory of your process. You can optimize your code, if necessary, for specific situations, skipping the functions of the libraries to manage the memory as you want.
And, for that matter, if you're not careful, you can corrupt the memory, write values where you should not, or read things that have not been written correctly.
But, in general, accessing random memory locations INSIDE your program is not an error in itself; in fact, it is perfectly valid (your code proves it).
Another thing very different is that we know what we are doing ...