Thread: bad c code question

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    630

    bad c code question

    Hello,

    I'm wondering why is the following code working (although it shouldnt):

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    main() {
    	char answer[1];
    	printf("question? ");
    	scanf("%s",answer);
    	printf("%s",answer);
    }
    It will print answer normally.

    Why is that?

    Thanks for explanation!

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You got lucky enough that there was nothing "important" behind answer -- answer is a legitimate memory address, and the result of the scanf is stored starting there. It will overwrite what's behind it (or raise an access violation if what's behind it is unavailable), 'cause that's just the way scanf is.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Stack alignment is probably 4 bytes so there are at least 3 bytes of padding
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Bad feeling about piece of code
    By Kurbein in forum C++ Programming
    Replies: 6
    Last Post: 06-16-2009, 12:13 PM
  2. Linked List question from a newb(Need code Critique)
    By Gatt9 in forum C++ Programming
    Replies: 2
    Last Post: 01-08-2006, 03:11 AM
  3. My First If Code, Question? :P
    By dimirpaw in forum C++ Programming
    Replies: 3
    Last Post: 11-29-2005, 08:49 PM
  4. Bad code examples
    By Monster in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 02-27-2003, 05:02 AM
  5. question regarding code found on this board
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 07-23-2002, 08:03 PM