Variable Length Arrays (VLA) are not part of Standard C++. Read more in Why aren't variable-length arrays part of the C++ standard?
But let's say, that you use a compiler extension that allows them, then the problem is that you use a C function here:
std::cout << strlen(a) << '\n';
which expects a C string, which means a NULL-terminated string.
That means that you should make your array big enough to hold the NULL termination character, like this:
char a[s.length() + 1];
since string::length()
will return 4 for the string "1010". That means that the C string should be this: "1010\0", i.e. the actual string, appended with the NULL terminating character. As a result, you would need an array of size 5 to store that string.
An easy fix would be:
char a[s.length() + 1] = {0};
which will NULL initialize every cell of the array. Then you will overwrite every cell of it with characters, except from the last cell, specially reserved for the NULL terminator.
Another approach would be to only assign the NULL terminator to the last cell of your string, like a[s.length()] = '\0';
. Notice how s.length()
now is the index to the last element of your array.
Standard C string functions (like strlen()
) depend on the NULL termination character to mark the end of the string. In the absence of that important character, they do not know when to stop, thus accessing memory beyond from the point they are meant to visit.
That invokes Undefined Behavior (UB), which, in your computer, is accessing memory with garbage values.