Click here to Skip to main content
15,867,954 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
guys, whats wrong here?
C++
#include <stdio.h>
int main()
{
    char *s,i;
    printf("Enter a string: ");
    scanf("%s",s);
    for(i=0; s[i]!='\0'; ++i);
    printf("Length of string: %d \n",i);
    return 0;
}


output:Enter a string: jeevan
Length of string: 6
Segmentation fault (core dumped)
Posted
Updated 17-Jul-14 21:51pm
v3

C++
char *s;
doesn't allocate any memory for the scanf read - it just declares a pointer - so you need to use (for example)
C++
s = malloc(100);
to get enough space for a 99 character string (plus the terminating nul) iirc

the issue then is, how do you ensure your user doesn't type more than 99 characters ? - and the answer is, using scanf like this, you cant - its 'dangerous'

[edit] I have seen talk of a specifier for scanf, that alludes to using "%ms" gets scanf to allocate the memory for you, but, I cannot attest to this form of usage [/edit]

[edit] I seem to remember that you could also a length specifier with scanf, but, you'd still have to use the malloc or declare s as an array of char, and, it gets messy when the user types over the number of characters you've allowed for [edit]

- you should use something safer, like fgets() instead

'g'
 
Share this answer
 
You have not allocate any memory for this string, the quick and dirty fix would be:

C#
#include <stdio.h>
int main()
{
    char s[255],i;
    printf("Enter a string: ");
    scanf("%s",s);
    for(i=0; s[i]!='\0'; ++i);
    printf("Length of string: %d \n",i);
    return 0;
}
 
Share this answer
 
A nice reading: "String overflows with scanf"[^].
 
Share this answer
 
Comments
Leo Chapiro 18-Jul-14 4:19am    
A good point, +5 from me :)
CPallini 18-Jul-14 4:25am    
Thank you.
Now, where is my 5? :-D :-D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900