0

Why do I have different output then expected when I input a word that has the same length (or bigger) as default char-array length

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

int main(int argc, char const *argv[])
{
    char word[4];
    printf("Write a string: ");
    scanf("%s", word);
    int lenght = strlen( word );
    int j = lenght-1;
    for (size_t i = 0; i < lenght/2; i++)
    {
        char temp = word[i];
        word[i]=word[j];
        word[j] = temp;

        j--;
    }

    printf("%s", word); //reversed string

    return 0;
}

e.g input is "kill"
expected output is "llik"
actuall output is lliki♦

but when I fill that array using scanf() with word "kill" and then use printf("%s",word) I see that there is no problems with having words longer than 4 in word[]

Roast Beef
  • 25
  • 6
  • 2
    If you want to store a **n** character string, you need an array of size **n+1**, as the last array element has to be a null termination ('\0' character). Therefore `word` has to be at least with size `[5]` to accomodate the word "kill". – wohlstad Jun 04 '22 at 16:25
  • 2
    You're seeing [*buffer overflow*](https://en.wikipedia.org/wiki/Buffer_overflow), which is a good example of [undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior), which means anything can happen. – Steve Summit Jun 04 '22 at 16:38
  • If you declare `char word[4]`, you should read into it with `scanf("%3s", word)`. If you want to read longer words, you should do something like `char word[20]` and then `scanf("%19s", word)`. – Steve Summit Jun 04 '22 at 16:40
  • If the linked Q&A is not helpful, please let me know. – n. m. could be an AI Jun 04 '22 at 19:04

1 Answers1

-2

Your program is OK

Here it seems that all is well

  • Undefined Behavior can be sneaky. Observing the behavior of a program does not ensure that its undefined behavior is OK. – Drew Dormann Jun 24 '22 at 17:02