So, if I want to declare an array of characters I can go this way
char a[2];
char * a ;
char * a = new char[2];
Ignoring the first declaration, the other two use pointers. As far as I know the third declaration is stored in heap and is freed using the delete operator . does the second declaration also hold the array in heap ? Does it mean that if something is stored in heap and not freed can be used anywhere in a file like a variable with file linkage ? I tried both third and second declaration in one function and then using the variable in another but it didn’t work, why ? Are there any other differences between the second and third declarations ?
a[2]stores 2 chars on the stack.ais an uninitializedpointer.
You are right in thinking that heap allocated variables can be shared across your process, however, you will need to ensure that you pass the location of the allocated heap memory around – you do this e.g. by returning
afrom your method or function, or by increasing the scope ofae.g. to class scope.deletewill free heap allocations. In your case,deleteshould only be used in scenario 3, since in #1, stack variables are cleaned up when they go out of scope, and in #2, you haven’t allocated any memory.Because the above can easily lead to chaos during the transfer of ownership over the heap allocations, smart pointers such as
auto_ptror boost’s shared_ptr can be used to make life simpler.