0

So I'm working on a documentary of learning the C Language and I want to make examples within pointers and input. Basically, I made a Hello, (name). program like this using C99:

#include <stdio.h>

int main() {
    char *name;
    printf("What's your name? ");
    scanf("%s", name);
    printf("Hello, %s.\n", name);
}

When I tried compiling it, the error it gave me was this:

C3.c:5:48: error: variable 'name' is uninitialized when used here [-Werror,-Wuninitialized]
    printf("What is your name? "); scanf("%s", name);
                                               ^~~~
C3.c:4:17: note: initialize the variable 'name' to silence this warning
    char *name;
               ^
                = NULL
1 error generated.
<builtin>: recipe for target 'C3' failed
make: *** [C3] Error 1

So I modified line 2 into char *result = "";, which actually worked this time, but the output was this:

What's your name? Bro
Segmentation fault

This is a little confusing for me, since I'm not actually used to the scanf() function.

So my problem is, what would be a better way to get strings by input using scanf() in C99 without any weird output right after?

Mureinik
  • 297,002
  • 52
  • 306
  • 350

1 Answers1

2

scanf doesn't allocate any memory. You need to allocate the string's memory yourself. You should also specify the length scanf is allowed to read to avoid buffer overflows.

E.g.:

char name[21]; // 20 chars plus the null-terminator
printf("What's your name? ");
scanf("%20s", name);
Mureinik
  • 297,002
  • 52
  • 306
  • 350