c++ primer says:
// C-style character string implementation
const char *pc = "a very long literal string";
const size_t len = strlen(pc +1); // space to allocate
// performance test on string allocation and copy
for (size_t ix = 0; ix != 1000000; ++ix) {
char *pc2 = new char[len + 1]; // allocate the space
strcpy(pc2, pc); // do the copy
if (strcmp(pc2, pc)) // use the new string
; // do nothing
delete [] pc2; // free the memory
we can count that string "a very long literal string" has 26 words, so len will be 25. but lets see this: char *pc2 = new char[len + 1]; . it means the size of pc2 will be 26. and then do the copy: strcpy(pc2, pc); . if we do so, we will only copy the first 26 words from pc to pc2, the remaining '\0' wont be a part of pc2. why do we do like this?? i think we should write "const size_t len = strlen(pc);" instead of "const size_t len = strlen(pc +1);" . am i right?
len is not a function. It is a variable. But it is defined by a function.
Now then why is len going to be 25? It's going to be 26 because there are 26 characters. Then you must add one for the null.
thats just why i asked this question. why did the author put the null beyond the end of the array? the array would not be a c-style string because he did so.. according to c++ primer , never forget the null after your c-style strings. maybe the author just wanna illustrate something, but he should explain clearly... beginner like me are always confused by unclear explanations like this.
The problem here is this particular line (as moorecm has aleady mentioned): const size_t len = strlen(pc +1); // space to allocate
That would give an incorrect value for the length of the string. It will be one short.
So this line: char *pc2 = new char[len + 1]; // allocate the space does not allocate enough characters.
So the string copy will cause a buffer overflow (heap corruption).
I checked the C++ primer book and hzesen1221 has copied the code the code as given in the book.