Thread: Storing string using fgets into an array

  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    14

    Storing string using fgets into an array

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
    
        char str[1];
        fgets(str, 100, stdin); //inputs hello
        printf("%s", str); //outputs hello
    
        return 0;
    }
    Why does this code work? There isn't enough space in the array to store the 6-char string (including the null-character) yet the program works.

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Just because a program compiles doesn't mean it is correct. You happen to be invoking Undefined Behaviour, which means anything can happen including the program appearing to run properly.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    Don't confuse 'works' with 'bug-free'.

    Because the stack needs to be kept aligned, the compiler is likely to round up small arrays to some multiple of 2,4,8,16 bytes.

    Your 6-byte string it would seem is just comfortably sitting in otherwise dead space.

    The same code with another compiler on another machine, with the same input could just as easily crash as 'work'.

    There is nothing in the standard that says a program should throw an exception every time you invoke undefined behaviour.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Storing a string inside an array?
    By tmac619619 in forum C Programming
    Replies: 16
    Last Post: 11-12-2012, 10:23 PM
  2. String Array fgets
    By deeisenberg in forum C Programming
    Replies: 2
    Last Post: 12-01-2011, 03:22 PM
  3. TinyXML reading XML and storing to string array
    By airesore in forum C++ Programming
    Replies: 9
    Last Post: 10-27-2011, 11:57 AM
  4. storing a string of binary into an array
    By daisy_polly in forum C Programming
    Replies: 5
    Last Post: 02-23-2006, 02:45 PM
  5. Storing multiple string in array
    By winsonlee in forum C Programming
    Replies: 2
    Last Post: 03-15-2004, 07:49 AM

Tags for this Thread