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


i know string literals stored in read-only memory ,so can't update them. what's wrong strlen() function.it works if initialize char *s within program. i.e

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

and doesn't when taking string user

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

you have allocate memory going read string. exampe

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

if declared s this

char *s; 

then pointer not initialized.

if declared s this

char *s="hey"; 

then scanf try change string literal results in undefined behaviour of program.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -