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!
The variable carr
is of type char[1]
which decays to char*
. When trying to print a char*
your debugger keeps printing chars until it reaches a null terminator \\0
.
It's not that carr
contains "ab"
, but rather that any function looking at carr
would assume that it does. This is because the bounds of the array are (almost always) discarded when it is passed to another function.
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'
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.