In C++, we can declare an array by using the new
operator:
char *p = new char[50]; // dynamically allocate an array of 50 char
This is useful in functions when we don’t know in advance how large the array should be or if we want to allocate the array in the heap instead of the stack (the equivalent in C would be to use malloc() or calloc() to allocate the array)
A common programming error (because it looks very similar and is perfectly valid) is to replace the [] with ().
char *p = new char(50);
In this case, we have allocated a single char and initialized its value to 50 – which is not what was intended.
This leads to those hard to track down bugs of corrupted data and / or random crashes.
NOTE: when freeing an array created with new
, remember to call delete[]
instead of delete
to avoid memory leaks (and definitely never call free()
)