-1

When I was practicing string in Hackerrank, they showed me a new approach to get string input in C that I had never seen before. This is code:

char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1); 

Can you explain that how these thing work? In a lot of program I always get string input by this way:

char *s[MAX_LEN];
fflush(stdin);
gets(s);

Thank you!

  • Fully explained [here](https://en.cppreference.com/w/c/memory/malloc). – Robert Harvey Jul 18 '21 at 17:14
  • 2
    Does your compiler shout some warning at you with the second code? If not, turn up your warning level. – Gerhardh Jul 18 '21 at 17:14
  • and [here](https://en.cppreference.com/w/c/memory/realloc). – Robert Harvey Jul 18 '21 at 17:14
  • 1
    Besides the memory handling stuff, you should never use `gets`. It is unsafe and obsoleted by the standard some decades ago. – Gerhardh Jul 18 '21 at 17:15
  • Please focus your question on which detail of the shown code you want explained. Do that e.g. by exaplaining as much as you can yourself, so that the gaps can be filled in by answers. Refer to the documentation for the functions you want explained. – Yunnosch Jul 18 '21 at 17:19
  • `char *s[MAX_LEN]; fflush(stdin); gets(s);` has problems: Likely meant `char s[MAX_LEN];` (no `*`), `fflush(stdin)` is UB. `gets(s);` no longer available since C11. `gets(s);` prone to overflow. – chux - Reinstate Monica Jul 18 '21 at 17:20
  • You can also focus your question by minimising the differences between the two code versions you show. If Three lines are different, focus is missing, if only half of one line is different, focus is good. – Yunnosch Jul 18 '21 at 17:26
  • The Hackerrank code is a security bug waiting to happen -- Do _not_ use it. As with `gets`, there is _no_ limit check on the input string length, so the buffer can be [deliberately] overflowed – Craig Estey Jul 18 '21 at 17:29
  • I consider both variants as bad code: Using `scanf()` for a string of unknown size, using `sizeof(char)`, `fflush(stdin)`, overwriting a pointer with a string.... – U. Windl Jul 21 '21 at 15:17

1 Answers1

1

scanf("%[^\n]", s); is worse than gets() to read a line.

It provides no width restriction leading to buffer overflow, fails to set s when input is "\n" and does not consume the trailing "\n".


Use fgets() to read a line of user input into a string.

To remove potential trailing '\n', see here.

fgets(buf, n, stdin) reads up to n-1 characters in a line. Additional code needed to consume excess input.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256