Why for loop doesn't work for 2D array with an overflow but still works for 1D array

Debojit Acharjee 455 Reputation points
2023-07-23T11:03:30.4133333+00:00

The for loop to store values to two 1D arrays can store and print values even with an overflow but why a program to store values to 2D array using for loop doesn't run when there is an overflow?

The following program runs:

#include <stdio.h>

int main()
{
    int i, a[5], b[6];

    for (i = 0; i <= 6; i++)
    {
        a[i] = i;
        b[i] = i;
    }

        for (i = 0; i <= 6; i++)
    {
        printf(" %d", a[i], b[i]);
    }
    
    return 0;
}



But why the following program doesn't run?

#include <stdio.h>

int main()
{
    int i, j, a[5][5];

    for (i = 0; i <= 5; i++)
    {
        for (j = 0; j <= 5; j++)
        {
            a[i][j] = j;
        }
    }


    for (i = 0; i <= 5; i++)
    {
        for (j = 0; j <= 5; j++)
        {
            printf(" %d", a[i][j]);
        }
        printf("\n");
    }

    return 0;
}
Developer technologies | C++
Developer technologies | C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other
A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 81,971 Reputation points Volunteer Moderator
    2023-07-24T15:12:42.4866667+00:00

    C allocation places static or stack variable allocations next to each other. So when you overrun a you are accessing b’s allocation. If you reversed the declaration order of a and b then an overrun of a would corrupt the stack.

    note: you should really use a better c compiler. Your examples often use uninitiated variables. Most modern c compilers mark the first page of memory as inaccessible, so a runtime error is thrown when accessing memory location zero.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.