T94j0
T94j0

Reputation: 87

Problems storing strings with scanf

I'm having problems with scanf in C. After reading other Stackoverflow posts on how to fix problems with scanf, I now know that scanf is not recommended, but I have to use it for a homework assignment. I am trying to store 3 string values that have a maximum size according to their buffer size. When I compile and run this program, I input the values 255 255 255 and this is what is printed.

1:
2:
3: 255

Here is the program source:

#include <stdio.h>
int main(){
     char first[8] = "", second[3] = "", third[3] = "";
     scanf("%8s %3s %3s", first, second, third);
     printf("1: %s\n2: %s\n3: %s", first, second, third);
}

Upvotes: 1

Views: 249

Answers (1)

chqrlie
chqrlie

Reputation: 144715

As currently defined, the arrays can only store very short strings:

  • char first[8] can only store 7 bytes and a null terminator,
  • char second[3] can only store 2 bytes and a null terminator,
  • char third[3] can only store 2 bytes and a null terminator.

The scanf format string should be:

scanf("%7s %2s %2s", first, second, third);

The current code invokes undefined behavior as you store strings longer than the array sizes for second and third.

To parse longer strings, you should define the arrays as

char first[9] = "", second[4] = "", third[4] = "";

And you should check the return value of scanf().

Upvotes: 1

Related Questions