Hello,
I have a kind of strange question here.
Consider the following function
1 2 3 4 5
void f()
{
int a = 1;
int *b = newint(1);
}
The first one is said to statically allocate the memory for that int, and the second to do it dynamically.
But what actually means dynamically and statically here ?
When the program is running, until we step into the functions these values will not be initialized.
And in runtime, when we execute this function due to some user interactions, the "a" variable is initialized to 1 and the "b" pointer is pointing to int with value 1. So they are both allocated in runtime. Am I right ?
I think I am misunderstanding something here. And I hope I formulated my question correctly, so you can understand me.
int a = 1; will allocate the variable 'a' for an int, and it will automatically be deleted at the end of the scope.
int *b = newint(1); will create a pointer to a new variable an create some memory space. However, it DOES NOT have a scope, and will never be deleted until you specifically say delete b;. Also, if you run this function, you will have a memory leak, because the pointer will go out of scope (not the 'memory' itself), and you will have no way to access and delete the variable.
In this thread were exposed some uses of dynamically allocated objects: http://www.cplusplus.com/forum/beginner/12467/
Another thing is that you will be able from function f to return the dynamically allocated memory address but the automatically allocated int will be destructed outside the function scope so you won't be able of returning an useful memory address