Segmentation fault while taking string from user

后端 未结 4 1037
说谎
说谎 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 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);
    }
    

提交回复
热议问题