0

Problematic program:

#include<stdio.h>
#include<string.h>
void main() {
char s[100],f[1];
scanf("%s",&s);
scanf("%s",&f);
printf("\n%s %s",s,f);
}

output is empty for s, while f is read properly. while if we switch f[1] and s[100], or initialise f with size larger than 1, or initialize any other larger than 1 array, then it works as it should. (this is a stripped down version of program, to the essential problematic part)

tried swapping f[1] and s[100] which works, but when placed in the mentioned order, it breaks.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
vbansal21
  • 1
  • 2
  • 1
    `f` can only hold a string of length 0. `scanf("%s",&f);` will result in _undefined behaviour_ (google that term) for any string entered longer than 0. Be aware that undefined behaviour includes "apparently working as I expect". – Jabberwocky Apr 19 '23 at 09:08
  • but the thing is, if I print s and f seperately, s is empty, while f shows the entered character. IDK why – vbansal21 Apr 19 '23 at 09:11
  • It's undefined behaviour. You're overwriting past the end of the `f` array and this yields undefined behaviour. – Jabberwocky Apr 19 '23 at 09:12
  • This is undefined behaviour. One possible speculation of what happens is that you read anything but `'\0'` into `f` and the terminator `'\0'` into the immediatly following `s` in memory. Which overwrites whatever you had there with the "empty" signaling terminator 0. – Yunnosch Apr 19 '23 at 09:12
  • so I printed it's pointer, and s preceeds f in memory space, so, should it overwrite it? – vbansal21 Apr 19 '23 at 09:14
  • I vote to close as another instance of the typo/thinko of forgetting the terminator. – Yunnosch Apr 19 '23 at 09:14
  • 2
    No not "it should overwrite it", it might. And next time it will format your harddisk. Undefined behaviour, really really important to understand. – Yunnosch Apr 19 '23 at 09:15
  • @vbansal21 if you want to know what is actually happening, you need to execute your code with a debugger stepping through the assembly code. – Jabberwocky Apr 19 '23 at 09:15
  • okay, sure, thanks for the info, and taking your time to reply. – vbansal21 Apr 19 '23 at 09:15
  • 1
    Never, never, never... do `scanf("%s" ....` It's just as bad as using `gets`. Always, always, always... use a "maximum field width" specifier. And that shall be (at most) array size minus 1. And that tells you why scanning into `f[1]` is meaningless. – Support Ukraine Apr 19 '23 at 09:22
  • `&s` in `scanf` is wrong. For arrays you don't use `&s` just use `s` – Support Ukraine Apr 19 '23 at 09:23
  • 2
    And always, always, always... check the return value of `scanf` – Support Ukraine Apr 19 '23 at 09:24

0 Answers0