Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

c - Why does strlen() return strange result when array doesn't contain null terminator?

I have two programs. Both initialize an array from a string literal. In one case the array size is exactly the number of characters I want to place in the array.

I wonder why the output of the size returned by strlen() differs for both prorgams. Is it because of the terminating null character is missing? If so, then why is the output 16?

#include<stdio.h>
#include<string.h>
main()
{
    char str[5] = "ankit";
    printf("size of = %d 
 ",sizeof(str));
    int len = strlen(str);
    printf("length = %d 
 ",len);
}

output :- size of = 5 , length = 16

#include<stdio.h>
#include<string.h>
main()
{
    char str[] = "ankit";
    printf("size of = %d 
 ",sizeof(str));
    int len = strlen(str);
    printf("length = %d 
 ",len);
}

output :- size of = 6 , length = 5

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your first code, by writing

 char str[5] = "ankit";

you don't have any space left for the null terminator to get stored, which is required to be there for str to be used as a string . So, in that case, strlen() invokes undefined behavior by overrunning the allocated memory in search of the null terminator.

OTOH, in the second snippet,

char str[] = "ankit";

you leave the size allocation to the compiler and it allocates memory for the elements in the string literal used as initializer plus the null terminator. So, you got the desired result.

IMO, always use the later approach, saves a lot of headache from time to time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...