Search code examples
cfgets

fgets segmentation fault when reading input from user


here's the offending code using ubuntu

char *name;

int main(void)
{
  fgets(name, sizeof(name), stdin);
}
void HUD()
{
  printf("%s ", name); 
}

Here's my problem. I started with scanf("%s", &name) and was getting junk at the end of the string. Through the last 2 hours have been reading docs on scanf, and fgets, because apparently scanf shouldn't be used when you don't know the size of the array you want, (and since user input can vary in size) I decided to try using fgets. I've also tried setting a fixed value both by char name[100]; and by fgets(name, 100, stdin)

Now I'm getting a segmentation fault, and through reading every result I found on the first 2 pages of google, my syntax appears correct, and I've found nothing on cboard or here to fix my problem.

Any ideas?


Solution

  • sizeof(name) Will be the size of the pointer on your system, on mine it's 8 bytes. Not the size of the buffer, as you might have been expecting

    Also char* name is uninitialised. You will try to write to an uninitialised buffer and it will end in undefined behaviour.

    To resolve either make it a fixed size buffer or allocate some space on the heap.

    Allocate

    #include <stdio.h>
    #include <stdlib.h>
    
    #define NAME_SIZE 100
    char *name;
    
    void HUD()
    {
      printf("%s ", name); 
    }
    
    int main(void)
    {
        name=calloc(NAME_SIZE, sizeof(char));
        fgets(name, NAME_SIZE, stdin);
    
        HUD();
    
        free(name);
    }
    

    Static Array

    #include <stdio.h>
    #include <stdlib.h>
    
    #define NAME_SIZE 100
    char name[NAME_SIZE];
    
    void HUD()
    {
      printf("%s ", name); 
    }
    
    int main(void)
    {
        fgets(name, NAME_SIZE, stdin);
    
        HUD();
    }
    

    You must pass the size of the buffer to fgets so it know how much space it has to write in to.