When you allocate memory for a string, you must always allocate one more byte than the length of the string. That extra byte is for the terminating ''
character.
If you have a string that happens to end in a newline
character, and you strip that character off, you will obviously make the string one character shorter, and this means you will need one less byte of memory to store it. But storing it will still require space for the
, as always.
As an example:
char string[] = "test
";
int stringlen = strlen(string); // length = 5
char *copy1 = malloc(stringlen + 1); // allocates 6 bytes
strcpy(copy1, string); // this works
char *p = strchr(string, '
'); // find the
if(p != NULL) *p = ''; // strip it off
printf("string is now: "%s"
", string);
stringlen = strlen(string); // length = 4
char *copy2 = malloc(stringlen + 1); // allocates 5 bytes
strcpy(copy2, string); // this works also
Now, if you wrote the code like this:
char string[] = "test
";
int stringlen = strlen(string);
char *p = strchr(string, '
');
if(p != NULL) *p = '';
printf("string is now: "%s"
", string);
char *copy = malloc(stringlen); // don't have to add 1,
// since I just stripped off
strcpy(copy, string);
it looks like you can get away with not adding the + 1
. But any time you have to add a comment to explain some code that's not there, and especially if the comment you have to write is longer than the code it replaces, it's usually a sign that you've gotten too clever, that you ought to just leave the code in. And, indeed, even though it might seem to work at first, writing the code this way would be pretty dangerous, because if you ever end up with a string that doesn't end in
, meaning that there's nothing to strip off, the code will stop working properly.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…