Words do not say, we all understand that the string is the end of the ' s ', but it is today programmed to forget to add ' to ', the result of a waste of time debugging to find, embarrassed dead.
First through a piece of code to see, forget to add ' to ' will cause what difficult to find trouble it
1#include <iostream>2#include <string>3 using namespacestd;4 intMain ()5 {6 Char*p;7 Char*q="AB";8p=New Char[2];9Cout<<strlen (P) <<Endl;Tencout<<sizeof(p); One return 0; A}
Running Result: 16,4
1, clearly assigned to p two bytes strlen (p) Why did it become 16? Don't worry, let's go inside the strlen () function.
int strlen (constchar * str) { int0; while (*str++ ) + +length ; return (length);}
The original strlen () is based on ' s ' to determine whether to the end of the string, and regardless of whether it has crossed the line, and the program runs at the time of the P pointer after the 16th (this is a random value according to different circumstances) A byte has a 0, so it is considered to be 16.
2. Why is sizeof (p) 4? Needless to say, p is a pointer, the sizeof pointer is a fixed value of 4 (64bit system is 8), do not understand please see my previous write about sizeof blog
3, since the use of sizeof and strlen method can not see how many bytes assigned to p, that single-step debugging always see? The answer is no, let's take a look
In short, the programming encountered in the string must be remembered at the end of the manual add '! '!!!! Remember, remember.
String processing always reminds yourself to manually add ' + ' at the end