1

Function to calculate string length; I think the logic here is correct:

int strlength(char *s)
{
 int count=0;   
 while(*s!='\0')
 {
    count++;
    s++;
 }
  return count;
}


int main(void) {
    char *s;
    int length;
    printf("enter your string ");
    scanf("%s",s);  
    length = strlength(s);
    printf("string length:%d",length);
    return 0;
}

Am I taking the string correctly here and assigning it? Can anyone please explain why I get segmentation fault here?

0

2 Answers 2

5

Your s has to point to something. Here is an example of allocating 128 bytes:

s = malloc(128);

Be sure to release the memory once you're done with it:

free(s);

Note that you must limit how much can be read from the user.

scanf("%127s", s);

I've left an extra byte for the NUL terminator.

Sign up to request clarification or add additional context in comments.

Comments

3

this second line of the main() function is declaring a pointer. However, that pointer is never initialized to point to some memory block that the program owns.

Suggest using one of the heap allocation functions (malloc, calloc, realloc) to initialize that pointer.

Using that uninitialized pointer is undefined behavior and (as you saw) leads to a seg fault event.

when calling any of the scanf() family of functions,

  1. always check the returned value (not the parameter values) to assure the operation was successful.
  2. when using the '%s' input/format specifier, always include a MAX CHARACTERS modifier that is one less than the length of the input buffer to avoid any buffer overflow. Such overflow is undefined behavior and can lead to a seg fault event.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.