hina abbasi
hina abbasi

Reputation: 455

scanf() not working properly?

  char *str;
  printf("Enter string:\n");
  scanf("%s",str);

OUTPUT: runtime-check failure#3 str is being used without being initialized

Upvotes: 2

Views: 1177

Answers (5)

Tonmoy
Tonmoy

Reputation: 557

You have to allocate memory before assigning some value to a pointer. Always remember that pointer points to a memory location and you have to tell him what memory location you want to assign for him. So, for doing that you have to do :

str = (char*)malloc(sizeof(char));

This will assign you 1byte of memory block. So, you can assign only one character in this memory block. For a string you have to assign as many blocks depending on the number of characters in the string.Say, "Stack" requires 5 character and 1 extra block for '\0'. So, you have to assign at least 6 memory block to him.

str =  (char*)malloc(6*sizeof(char));

I hope this will help you to grow more concepts in C.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 754880

Allocate an array and read into that:

char str[100];

if (scanf("%99s", str) != 1)
    ...error...

Or, if you need a pointer, then:

char data[100];
char *str = data;

if (scanf("%99s", str) != 1)
    ...error...

Note the use of a length to prevent buffer overflow. Note that the length specified to scanf() et al is one less than the total length (an oddity based on ancient precedent; most code includes the null byte in the specified length — see fgets(), for example).

Remember that %s will skip past leading white space and then stop on the first white space after some non-white space character. In particular, it will leave the newline in the input stream, ready for the next input operation to read. If you want the whole line of input, then you should probably use fgets() and sscanf() rather than raw scanf() — in fact, very often you should use fgets() and sscanf() rather than scanf() or fscanf(), if only because it make sensible error reporting a lot easier.

Upvotes: 3

halfbit
halfbit

Reputation: 3464

You might NOT want to use exactly scanf("%s") (or get in the habit of using it) as it is vulnerable to buffer overflow (i.e. might accept more characters than your buffer can hold). For a discussion on this see Disadvantages of scanf

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172608

Its an undefined behavior if you dont initialize it.You have an uninitialized pointer which is reading data into memory location which may eventually cause trouble for you. You've declared str as a pointer, but you haven't given it a valid location to point to; it initially contains some random value that may or may not be a writable memory address.Try to allocate memory to the char *str;

char *str = malloc(sizeof(char)*100);

Upvotes: 1

haccks
haccks

Reputation: 106102

char *str declares str as a pointer to char type. scanf("%s",str) will read only E from the entered string.

Upvotes: 0

Related Questions