Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange thing with C++ memory management

Consider the output of this code:

char A = 'a';
char B[] = "b";
cout<<&A;

It outputs "ab" (the concatenation of A and B) and I wonder why. Please, explain me this.

like image 721
qtug Avatar asked Jan 17 '17 12:01

qtug


1 Answers

Because &A is a char *. A string, represented by a char *, is required to have a '\0' terminating byte.

&A points to a single char, without a following '\0'. As such, attempting to print this text string results in undefined behavior.

like image 112
Sam Varshavchik Avatar answered Oct 31 '22 18:10

Sam Varshavchik