简体   繁体   中英

Wrong strlen output

I have the following piece of code in C:

char a[55] = "hello";
size_t length = strlen(a);
char b[length];
strncpy(b,a,length);
size_t length2 = strlen(b);
printf("%d\n", length);          // output = 5
printf("%d\n", length2);         // output = 8

Why is this the case?

必须为'b [length +1]'。strlen在c字符串的末尾不包含空字符。

You never initialized b to anything. Therefore it's contents are undefined. The call to strlen(b) could read beyond the size of b and cause undefined behavior (such as a crash).

b未初始化:运行程序时,它包含RAM中的所有内容。

For the first string a, the length is 5 as it should be "hello" has 5 characters.

For the second string, b you declare it as a string of 5 characters, but you don't initialise it, so it counts the characters until it finds a byte containing the 0 terminator.

UPDATE : the following line was added after I wrote the original answer.

strncpy(b,a,length);

after this addition, the problem is that you declared b of size length, while it should be length + 1 to provision space for the string terminator.

Others have already pointed out that you need to allocate strlen(a)+1 characters for b to be able to hold the whole string.

They've given you a set of parameters to use for strncpy that will (attempt to) cover up the fact that it's not really suitable for the job at hand (or almost any other, truth be told). What you really want is to just use strcpy instead. Also note, however, that as you've allocated it, b is also a local ( auto storage class) variable. It's rarely useful to copy a string into a local variable.

Most of the time, if you're copying a string, you need to copy it to dynamically allocated storage -- otherwise, you might as well use the original and skip doing a copy at all. Copying a string into dynamically allocated storage is sufficiently common that many libraries already include a function (typically named strdup ) for the purpose. If you're library doesn't have that, it's fairly easy to write one of your own:

char *dupstr(char const *input) {
    char *ret = malloc(strlen(input)+1);
    if (ret)
        strcpy(ret, input);
    return ret;
}

[Edit: I've named this dupstr because strdup (along with anything else starting with str is reserved for the implementation.]

Actually char array is not terminated by '\\0' so strlen has no way to know where it sh'd stop calculating lenght of string as as its syntax is int strlen(char *s)-> it returns no. of chars in string till '\\0'(NULL char) so to avoid this this we have to append NULL char (b[length]='\\0')

otherwise strlen count char in string passed till NULL counter is encountered

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