I was just wondering what does my OS do if it ran out of memory and I wrote the following code.
int main() {
int *p;
while(1) {
p = new int;
}
}
But as I began to print the address of p and to my surprise the memory usage didn't blow up. It remains constant. And after each iteration the address of p is same as that of previous one.
#include <iostream>
int main() {
int *p;
while(1) {
p = new int;
std::cout << &p << std::endl;
}
}
I was wondering how std::cout << &p << std::endl;
is affecting memory?
CodePudding user response:
This code
std::cout << &p << std::endl;
does not print the address of the allocated memory, it prints the address of the variable p
.
To print the address of the allocated memory drop the &
.
std::cout << p << std::endl;
CodePudding user response:
When you use the "&" notation, it means that you get the address of a variable which means the place you store this variable.
p is a 8 byte variable (64-bit machine) in your code, so if you out put the address of p, it's just the place the OS decide to put it, which remains constant.
Instead, what you want is to output the place where p's value points to.
So just output the value of p is enough
#include <iostream>
int main() {
int *p;
while (1) {
p = new int;
std::cout << p << std::endl;
}
}