简体   繁体   中英

C++ Length of char* does not make sense?

I encounter this problem twice today, and I don't know where is the bug nor how to fix it.

#include <string.h>

char *str1 = "ab";
int length = strlen(str1);
char *str2 = new char[length + 1];

So when I test it with a few more lines:

cout << "Length of str1 = " << strlen(str1) << "\n";
cout << "Value of int length = " << length << "\n";
cout << "Length of str2 = " << strlen(str2) << "\n";

It gives me:

Length of str1 = 2

Value of int length = 2

Length of str2 = 48

I don't understand, 2 + 1 should be 3. The Length of str2 does not match what I initialize it. How can I fix this, please help, thanks.

The strlen function does not measure the size of a char array like str2 . It measures the offset of the first byte equal to '\\0' . Since the array is uninitialized, that might be anywhere in the memory you're not usnig after the array's end.

Length of C string depends on the content of the string, not on the memory allocated to the string's content. If you would like to get the correct length, you must copy the content of the original into the destination string, like this:

char *str1 = "ab";
int length = strlen(str1);
char *str2 = new char[length + 1];
strcpy(str2, str1);

What you have now is undefined behavior , when strlen passes the end of the allocated str2 in search for null terminator, and stops only 48 bytes later, deep into memory that has not been allocated to str2 variable.

I need to copy only part of str1 for example, str1 = "Hello World", and I need to copy from index = 4 to index = 7

Use memcpy , and null-terminate the string after that:

char *str = "Hello, world!";
int start = 4;
int end = 7;
int len = end-start+1;
char *str2 = new char[len+1];
memcpy(str2, str1+start, len);
str2[len] = '\0';

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM