Thread: BUFSIZ question

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    119

    BUFSIZ question

    I was under the impression that BUFSIZ is the size of the buffer, however, if you declare an array and make it's size bufsiz, then use fgets(array, BUFSIZ, stdin); it still seems possible to overflow the buffer. But if BUFSIZ is the size of the buffer, why doesn't this prevent overflowing it?

    Also, another small question:

    Code:
    while ((cb=getchar()) != EOF) {
    
    if (cb == '<') {
    
    printf("----------->");
    
    putc(cb);
    
    }
    I was trying to make a program to help me out with something in another program I made, hence the code above. It's supposed to wait until the user types "<", then automatically change that to "<------------------>". but it doesn't work, and I was hoping someone might know why.

    As always, thanks

    --Ash

  2. #2
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    getchar() waits for the user to press enter, so you would have to type '<' then press enter. If you want something that you described you'd have to use some nonstandard functions like Borland's getch() for Windows or the ncurses library for Linux that would allow you to get characters without waiting for newline.

    And doesn't putc() take a file stream as second argument?

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > But if BUFSIZ is the size of the buffer, why doesn't this prevent overflowing it?
    BUFSIZ is a constant defined in stdio.h, which is vaguely related to the optimal buffer size for your current implementation (but always at least 256). Specifically, it is the size of the buffer which setbuf() uses by default.

    char b1[10];
    char b2[BUFSIZ];
    fgets( b1, sizeof b1, stdin );
    fgets( b2, sizeof b2, stdin );
    The overflow protection comes from telling fgets the size of the buffer, not the actual size of the buffer.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM