I'm learning Cpp recently, and today when I use Clion to learn do some testing strange thing happened.
Here is my code
int main() {
char c = 'b';
char carr[1]{'a'};
char *p1 =&(carr[0]);
char *p2 =&c;
return 0;
}
Complier:
4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.8)
lldb :
And here is the details of memory:
Please help me to figure out the reasons!
That's the lldb data formatter for strings being a little too eager.
People looking at char arrays in the debugger don't generally want a char[N] to print as an array of N char's, they want to see it as a string. So lldb provides a "data formatter" for char[*] that presents it as a C string. The formatter really should hand-null terminate that string at the length of the array. You can see the (overly simplistic) data formatter by doing:
(lldb) type summary info carr
summary applied to (char [1]) carr is: `${var%s}` (hide value) (skip pointers)
It just says start at the start of the array and print the memory as a C-string.
You can see the real array by turning off the data formatter for char types with the --raw option when you print the variable:
(lldb) v --raw carr
(char [1]) carr = {
[0] = 'a'
}