#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    132
    Rep Power
    2

    Question about array overrun


    Hi, guys.

    i have a question about array:
    i know that this code:

    Code:
    int main()
    {
        int array[20];
           array[23]=15;
    }
    is wrong and will probably run over some memory data segments,

    but what about this:
    Code:
    int main()
    {
        int array[20];
           array[-2]=15;
    }
    will the program assign the '15' to the *(array-2) memory block, or will it just ignore it?

    thanks in advanced!
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,376
    Rep Power
    1871
    > will the program assign the '15' to the *(array-2) memory block, or will it just ignore it?
    Yes, it will overwrite 'something', with the usual range of unpredictable results that you would normally expect from running off the other end of the array.
    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
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    132
    Rep Power
    2
    Originally Posted by salem
    > will the program assign the '15' to the *(array-2) memory block, or will it just ignore it?
    Yes, it will overwrite 'something', with the usual range of unpredictable results that you would normally expect from running off the other end of the array.
    OK thanks!
  6. #4
  7. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,317
    Rep Power
    7170
    Out of curiosity, does c process array indexes as signed integers, or would that depend on the compiler?
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around
  8. #5
  9. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,376
    Rep Power
    1871
    Originally Posted by c99
    6.5.2.1 Array subscripting
    Constraints
    1
    One of the expressions shall have type ‘‘pointer to object type’’, the other expression shall have integer type, and the result has type ‘‘type’’.
    It would seem that they are integers.
    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

IMN logo majestic logo threadwatch logo seochat tools logo