Why the unexpected amount of symbols seen after dynamic memory allocation of array?
test
refers to c-string
. End of c-string
is marked by \0
.
test
isn't explicitly initialized in the program posted in the question. test
has indeterminate value and so you can't expect \0
to be present exactly after the end of c-string
.
The extra characters that you see in your debugger are those that exist between the last character pointed to by test
and the first \0
that the debugger found.
Why it is said that test
has indeterminate value?
When you use new
as in below statement,
unsigned char *p_dynamic_alloc = new unsigned char[8];
a pointer to unsigned char
is returned, which points to the address of the first element of the array. Dynamic memory of size: 8 * sizeof (unsigned char)
is allocated. Initializer is not mentioned.
Lets understand how new
handles dynamic allocation without the initializer:
[C++11: §5.3.4/15]: A new-expression that creates an object of type T initializes
that object as follows:
- If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value.
- Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.
Lets understand if it is really default initialized or if no initialization is performed.
Default initialization (of an unsigned char*
) is stated as,
[C++11: §8.5/7]:To default-initialize an object of type T means:
- if T is a (possibly cv-qualified) class type (Clause 9), the default constructor (12.1) or T is called (and the initialization is ill-formed if T has no default constructor or overload resolution (13.3) results in an ambiguity or in a function that is deleted or inaccessible from the context of the initialization);
- if T is an array type, each element is default-initialized;
- otherwise, no initialization is performed.
which means as pointed out earlier, the object has indeterminate value.
Solution
Properly initialize your dynamic byte array:
byte *test = new byte[8]();