0

Am I using scanf() in some wrong way?

char *input;
scanf("%s", input);
printf("%s\n", input);

This fails at the run-time.

BlueFlame
  • 31
  • 1
  • 1
  • 5

3 Answers3

6

Declaring a char * only creates a pointer, it does not allocate any memory for the string. You need to allocate memory for input. You can do that dynamically via malloc (and free when done) or you can declare an array of static size like char input[100].

taskinoor
  • 45,586
  • 12
  • 116
  • 142
  • how can I use malloc() if i don't know the size of my string beforehand? – BlueFlame Jun 07 '13 at 11:41
  • You need to assume some maximum size. Or if maximum size assumption is not possible then you can read chunk-by-chunk in a loop, e.g. read chunk of 1000 characters and append it to a buffer, then read next chunk of 1000 more characters and go on like this until you reach the end. – taskinoor Jun 07 '13 at 11:45
  • Which is why `scanf()` is not safe, at least traditionally. This [link](http://stackoverflow.com/questions/1621394/how-to-prevent-scanf-causing-a-buffer-overflow-in-c) discusses some methods to overcome this. – n3rd4n1 Jun 07 '13 at 11:49
  • @n3rd4n1, yes input without bound checking is risky. It's the same reason that `fgets` is more preferable to `gets`. – taskinoor Jun 07 '13 at 11:51
  • @taskinoor If I could do what you just said, I would not be asking such a basic question here. – BlueFlame Jun 07 '13 at 11:52
  • @BlueFlame, to input a string you need to allocate memory. That's how C works. There is no way to bypass that. In many situations assuming a max size is enough and you can declare array with static size. But if that is not enough for your situation then you have to choose more sophisticated solution. – taskinoor Jun 07 '13 at 11:55
2
char *input;

This is a pointer. It doesn't point to any memory.

#include <stdlib.h>
#include <stdio.h>

int main()
{
    //char *input;
    char input[128];
    memset(input, 0 ,sizeof(input));
    scanf("%s", input);
    printf("%s\n", input);
    return 0;
}
Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
alexis
  • 569
  • 5
  • 12
0

replace char *input; with char input[1024] = {0};

you should ensure the parameter you pass to scanf points to a buffer which could hold your input

akawhy
  • 1,558
  • 1
  • 11
  • 18