I think there is
no such thing as a "global" pointer. If you
dynamically allocate some memory, e.g. via C-style
malloc()
function or via C++-sytle
new
operator, then you get a
pointer to that memory block. And, in order to avoid
memory leaks, you will have to de-allocate that memory, by using
free()
or
delete
(or
delete[]
), respectively, when the memory block is
no longer needed.
Where you store the pointer doesn't really matter.
Yes, you
can store a pointer to
dynamically allocated memory in a "global"
variable. But that does
not make it a different kind of pointer. It does
not change anything about the requirement to de-allocate the dynamically allocated memory when you are done using it! The only thing that changes when you store the pointer in a "global" variable is that it becomes much more difficult to figure out
who might be accessing that pointer...
In any case: Whenever you
dynamically allocate some memory, you should always decide
who "owns" that memory. The owner should be responsible for de-allocating the memory when it is
no longer needed.
Furthermore, since you want to avoid
"use after free" or
"double free" vulnerabilities in your program, I suggest you explicitly set the "global" pointer variable to
NULL
after de-allocating the memory.
You can use tools like
Valgrind (Linux) or
Dr. Memory (Windows) to detect memory leaks in your program:
-
https://valgrind.org/
-
https://drmemory.org/