Thread: How is this possible?

  1. #1

    How is this possible?

    #include <stdio.h>

    int main() {

    char name[4];
    printf("enter name: ");
    printf("Hello %s",name);

    return 0;

    Out put:

    enter name: 012345
    Hello 012345

    How come it doest error ?
    char name[4]
    should only hold 3 characters w. a null at the end.
    Why is this case different?

  2. #2
    Registered User
    Join Date
    Oct 2001
    Try running the program a few times in a row. this may cause the program to crash. it should not work but it writes over memory if should not have access to so better to use the right sized arrays.
    Dangerous Dave

  3. #3
    Yes I know this,
    But why did it even work.
    That was my whole point.

    Even if it over rights the buffer im still printing out to stdout name[4].
    Not name[5] or [6]

    So again, why is it printing the extra memory spaces

  4. #4
    Aren't you overwriting the null?

  5. #5
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    You are outputting the string that starts at name[0], printf() does not know how long the string is, (that is why you use a NULL to terminate it). You have overwritten the memory locations after the last element of name[], if there is nothing there your program relies on later, you will get away with that, it may work sometimes and not others, it just depends what is there. C does nothing to protect you from yourself.
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  6. #6
    Budding Synth Programmer samGwilliam's Avatar
    Join Date
    Feb 2002
    Well it works because the compiler doesn't know how long the string typed in is going to be. There isn't a "This char array isn't long enough to be considered practical for string storage purposes" warning.

    Anyway, as we all know, C trusts the programmer so it lets you get away with things you really shouldn't be doing.

Popular pages Recent additions subscribe to a feed