Thread: buffer overflow with gcc but now with visual C++? why?

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    78

    buffer overflow with gcc but now with visual C++? why?

    Code:
    fflush(stdin);
    
    	for (i=0; i<=length-1; i++)
    	{if (i<=length-1){c=getchar();	input[i]=c;}}
    	input[length]=0;
    This code works in VisualC++, and if I enter too many letters it just truncates the string; but in gcc I get a buffer overflow and the program crashes. ?? Is there a better way to take user input and crop it as a string of a specified yet variable size?

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Most likely because of your screwball loop structures...
    Code:
    for (i = 0; i < length; i++)
      { input[i] = getchar();}
    
    input[length-1] = 0;

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You don't need that if there, since you've already guaranteed that to be true:
    Code:
    	for (i=0; i<=length-1; i++)
    	{if (i<=length-1){c=getchar();	input[i]=c;}}
    Here is your problem:
    Code:
    input[length]=0;
    Does this:
    Code:
    #define length 3000
    int input[ length ];
    ...
    input[ length ] = 0; /* You just ran off the end of your array. */

    Quzah.
    Last edited by quzah; 06-21-2011 at 03:39 PM.
    Hope is the first step on the road to disappointment.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > buffer overflow with gcc but now with visual C++? why?
    Actually, it's buffer overflow with gcc, why isn't it detected by VC++.
    The answer is basically luck - you were lucky that it crashed with gcc.


    The fflush(stdin) isn't doing you any favours either (see the FAQ).

    > Is there a better way to take user input and crop it as a string of a specified yet variable size?
    Read ALL input with fgets(), then decide what to do with it once it is in a buffer.
    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. strcmp buffer overflow
    By ligrec in forum C Programming
    Replies: 12
    Last Post: 11-18-2010, 10:35 AM
  2. buffer overflow
    By cpp_is_fun in forum C Programming
    Replies: 2
    Last Post: 10-24-2006, 11:04 PM
  3. Buffer overflow issue.
    By caroundw5h in forum C Programming
    Replies: 3
    Last Post: 12-27-2003, 12:13 PM
  4. buffer overflow problems
    By neandrake in forum C++ Programming
    Replies: 13
    Last Post: 12-04-2003, 08:02 AM