简体   繁体   中英

segmentation fault (core dumped) when taking a string from user and finding its length using strlen()

I know that string literals are stored in read-only memory ,so you can't update them. But what's wrong with strlen() function.it works if i initialize char *s within the program. ie

char *s="hey";
length=strlen(s);
printf("%d\n",length);// this works  

and doesn't when taking string from user

char *s;
int length;
scanf("%s",s);
length=strlen(s);
printf("%d\n",length); //this doesn't. gives segmentation fault  

You have to allocate memory where you are going to read a string. For exampe

char s[20] = { '\0' };
int length;
scanf("%19s",s);
length=strlen(s);
printf("%d\n",length); 

If you declared s like this

char *s;

then the pointer is not initialized.

If you declared s like this

char *s="hey";

then scanf will try to change the string literal that results in undefined behaviour of the program.

strlen searches for the null to determine the length. If the string is not null terminated then it will give length to the size of the variable. Here in you case you didnt allocate memory,neither it is null terminated.

I hope you got what you are looking for

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