Here’s my best guess at the code you meant:
#include <iostream>
using namespace std;
char *mystring = "thestring"; // extremely dangerous type mismatch, don't do this
int msize = 200;
int myfunc(int x)
{
int y = 20;
x = x + y;
return x * y;
}
int main(void)
{
int *px = new int;
cin >> *px;
cout << myfunc(*px);
delete px;
return 0;
}
The variables ‘mystring’ and ‘msize’ are global variables whose memory is statically allocated by the compiler. These variables exist for the entire duration of any run of the program and, typically, can be accessed by name by any part of your program.
‘x’ and ‘y’ are local variables to the function ‘myfunc.’ They exist and are accessible by name only within each call to that function.
‘px’ is a local variable to the function ‘main.’ ‘main’ is somewhat special in that, typically, it is the entry point for your program and when it returns the program exits. So, ‘px’s lifetime is essentially for the duration of the program although it can only be accessed by that name within the ‘main’ function.
‘new int’ explicitly dynamically allocates memory for an int that is then available until it is deallocated by a matching, explicit call to delete.
Typically, memory for a local variable is pushed onto (and popped off of) a running thread’s stack as the thread enters and exits from the variable’s scope (with constructors and destructors being called as appropriate too). Dynamically allocated memory is ultimately, explicitly managed per variable through calls to new and delete in C++ (or malloc and free in C).
0
solved How are classes managed in C++ memory management – study