Segmentation fault while taking string from user

后端 未结 4 1036
说谎
说谎 2021-01-29 13:07

Code:

int main()
{
  char *name=NULL;
  int n;
  printf(\"\\nenter the string\\n\");
  scanf(\"%s\",name);
  n=strlen(name);
  printf(\"%d\",n);
  return 0;
}


        
相关标签:
4条回答
  • 2021-01-29 13:46

    You didn't allocate any memory for pointer to char name.

    Example:

    char * name = malloc( sizeof( char ) * MAX_STRING_LENGTH ) ;
    
    0 讨论(0)
  • 2021-01-29 13:47

    Try this,

    int main()
    
    {
      char *name = malloc(sizeof( char ) * LENGTH); // define LENGTH as you desired
    
      int n;
      printf("\nenter the string\n");
      scanf("%s",name);
      n=strlen(name);
      printf("%d",n);
    
      free(name);
    }
    

    Problem is you did not allocate memory for pointer. So allocate memory tp pointer with malloc(BUFSIZE). Also at the end you have to free your allocated memory with free(name).

    0 讨论(0)
  • 2021-01-29 14:04

    C is not a managed language, so you need to tell your string (char *) wihch lenght of memory are you giving it. Here comes the malloc function.

    By the way, there is no GarbageCollector, so you'll need to free your char * when you'll have finish to use it.

    But be careful, malloc can return null, so your char * would be unable to store any char !

    int main(int argc, char **argv)
    {
        char *name = null;
        // Malloc your char *
        if ((name = malloc(sizeof( char ) * LENGTH_OF_YOUR_LARGER_INPUT)) == null)
        return;
        int n;
        printf("\nenter the string\n");
        scanf("%s",name);
        n=strlen(name);
        printf("%d",n);
        // Free the allocated memory to your char *
        free(name);
    }
    
    0 讨论(0)
  • 2021-01-29 14:12

    Instead of char * name = malloc( sizeof( char ) * MAX_STRING_LENGTH ) ;

    USE

     char * name = malloc(MAX_STRING_LENGTH+1 ); //+1 is to store Null character 
    

    and sizeof(char)==1 so you can avoid it.

    0 讨论(0)
提交回复
热议问题