I'm studying c++ and I'm reading about pointers. I'm curious about the following scenarios:
Scenario 1:
If I'm not mistaken, if the user types -1
, there will be a memory leak:
#include <iostream>
using namespace std;
int main(){
int *p = new int;
cout << "Please enter a number: ";
cin >> *p;
if (*p == -1){
cout << "Exiting...";
return 0;
}
cout << "You entered: " << *p << endl;
delete p;
return 0;
}
Scenario 2:
But what happens in the following code? From what I've read and correct me if I'm wrong, when declaring a pointer like in the second scenario the pointer gets cleared out once you are out of scope. So if the user doesn't enter -1
, the *p
will be auto-cleared?
#include <iostream>
using namespace std;
int main(){
int x;
int *p = &x;
cout << "Please enter a number: ";
cin >> *p;
if (*p == -1){
cout << "Exiting...";
return 0;
}
cout << "You entered: " << *p << endl;
return 0;
}
What happens if I enter -1
in the second scenario?