seems to reserve memory automatically. There is no malloc.
Dynamic allocation is not the only way to acquire memory in C++.
The variable p
has automatic storage. The string literals are arrays that have static storage. Objects with automatic, static or thread local storage are destroyed automatically. All variables have one of these three storage durations.
Automatic objects are destroyed at the end of the (narrowest surrounding) scope, static objects are destroyed after main
returns and thread local objects are destroyed when the thread exits.
Is this C/C++ standard or compiler specific?
The example program is mostly standard, except:
- You haven't included a header that is guaranteed to declare
malloc
.
- You haven't created
char*
objects into the dynamically allocated memory, so the behaviour of the program is technically undefined in C++. See P.P.P.S. below for how to fix this.
P.S. It is quite unsafe to point at string literals with non-const pointers to char. Attempting to modify the literal through such pointer would be syntactically correct, but the behaviour of the program would be undefined at runtime. Use const char*
instead. Conveniently, you can get rid of some of the explicit conversions.
P.P.S. C-style explicit conversions are not recommended in C++. Use static_cast
, const_cast
or reinterpret_cast
or their combination instead.
P.P.P.S. It is not recommended to use malloc
in C++. Use new
or new[]
instead... or even better, see next point.
P.P.P.P.S. It is not recommended to have bare owning pointers to dynamic memory. Using a RAII container such as std::vector
here would be a good idea.
P.P.P.P.P.S. Your example program leaks the dynamic allocation. This is one of the reasons to avoid bare owning pointers.
So p is allocated on the STACK pointing to a block of memory (array) in the HEAP where each element points (is a pointer) to a literal in the DATA segment?
The language itself is agnostic to concepts such as stack and heap memory and data segment. These are details specific to the implementation of the language on the system that you are using.