Tony Johansson wrote:
Hello Experts!!
When you instansiate varaibles(object) you can do so in four different scops
which are.
Within a block which is called Local or block scope .
Within a function which is called function scope.
Whithin a class which is called class scope.
Outside a function which is called global or file scope.
Now to my question when you allocate memory dynamically you can't say
anything about the scope because as long as you have the pointer you can
access the allocated memory anytime. I'm I right?
many thanks!
//Tony
No, scope does not define from where you may access memory. All of your
examples refer to the scope of a _name_, that is, where in the program
it's legal to refer to some named entity. If you assign a name to some
dynamically allocated memory, then the usual scope rules apply to the
name, irrespective of what happens to the memory. The name may go out
of scope while the memory persists (a potential source of memory leaks)
or the name may remain in scope after the memory has been freed (a
potential source of undefined behavior).
On a related note, there's nothing special about accessing dynamically
allocated memory. You can use the address of (&) operator to take the
address of stack objects too, but you do need to be mindful of the
temporary nature of such objects if you plan to do anything useful with
the contents of that memory.