Thread: Array bounds checking

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    31

    Array bounds checking

    Hi all,
    I need to include array bounds checking in the programs i write.
    With strings i use the following for bounds checking :
    Code:
    char s[100];
    scanf("%100s",s);
    How could I implement bounds checking on a integer array?
    Code:
    int a[10];
    int i;
    for(i=0;i<10;i++)
              scanf("%d",&a[i]);
    Here a user could enter several integers (>10) separated by whitespaces which would result in overflow. How can I check this?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    your loop scans only 10 numbers - so where do you see an overflow?
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    With

    Code:
    int a[10];
    int i;
    
    for (i = 0; i < 10; i++)
      scanf("%d", &a[i]);
    It does not matter whether the user chooses to enter ten integers on one line or one on each line, there is no overflow problem.

    However, for string reading, you should be taking the null character into account:

    Code:
    char word[100];
    
    scanf("%99s", word);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  3. Array bounds overflow
    By athos in forum C++ Programming
    Replies: 3
    Last Post: 08-10-2004, 12:05 PM
  4. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM
  5. Replies: 5
    Last Post: 05-30-2003, 12:46 AM