What happens when you have the following code:
void makeItHappen() { char* text = "Hello, world"; }
Does text
go out of scope and get deleted automatically or does it stay in the memory?
And what about the following example:
class SomeClass { public: SomeClass(); ~SomeClass(); }; SomeClass::SomeClass() { } SomeClass::~SomeClass() { std::cout << "Destroyed?" << std::endl; } int main() { SomeClass* someClass = new SomeClass(); return 0; } // What happend to someClass?
Does the same thing occur here?
Thanks!
A pointer is a variable that contains a memory location. Like all variables, it can be on the heap or the stack, depending on how it's declared. It's value -- the memory location -- can also exist on the heap or the stack. Typically, if you statically allocate something, it's on the stack.
Scope Resolution Operator is used to access static or class members whereas this pointer is used to access object members when there is a local variable with same name.
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C is used to allocate memory dynamically i.e. at run time.
A pointer variable can be in global or local scope and can also point to a variable that is in global, local, or no scope (as if it were coming off of the heap or addressing some DIO lines).
char* text = "Hello, world";
Here an automatic variable (a pointer) is created on the stack and set to point to a value in constant memory, which means:
""
exists through the whole program execution.When the pointer goes out of scope, the memory pointer itself (4 bytes) is freed, and the string is still in the same place - constant memory.
For the latter:
SomeClass* someClass = new SomeClass();
Then someClass
pointer will also be freed when it goes out of scope (since the pointer itself is on the stack too, just in the first example)... but not the object!
The keyword new
basically means that you allocate some memory for the object on free store - and you're responsible for calling delete
sometime in order to release that memory.
Does
text
go out of scope
Yes! It is local to the function makeItHappen()
and when the function returns it goes out of scope. However the pointed to string literal "Hello, world";
has static storage duration and is stored in read only section of the memory.
And what about the following example:
......
Does the same thing occur here?
Your second code sample leaks memory.
SomeClass* someClass = new SomeClass();
someClass
is local to main()
so when main returns it being an automatic variable gets destroyed. However the pointed to object remains in memory and there's no way to free it after the function returns. You need to explicitly write delete someClass
to properly deallocate the memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With