How is static array expanding itself?

105 Views Asked by At

I wrote a code for entering element and displaying the array at the same time. The code works but since char A[4] is static memory why does not it terminate/throw error after entering more than four elements? Code:

#include <iostream>
using namespace std;
void display(char arr[],int n)
{
    for(int i=0; i<n; i++)
    cout<<arr[i]<<" ";
    return;
}

int main()
{
char A[4];
int i=0;
char c;
for(;;)
{
    cout<<"Enter an element (enter p to end): ";
    cin>>c;
    if(c=='p')
        break;
    A[i]=c;
    i++;
    display(A,i);
    system("clear");
}
return 0;
}
2

There are 2 best solutions below

1
On

The code works but since char A[4] is static memory why does not it terminate/throw error after entering more than four elements?

The code has a bug. It will not work correctly until you fix the bug. It really is that simple.

1
On

Writing outside of an array by using an index that is negative or too big is "undefined behavior" and that doesn't mean that the program will halt with an error.

Undefined behavior means that anything can happen and the most dangerous form this can take (and it happens often) is that nothing happens; i.e. the program seems to be "working" anyway.

However maybe that later, possibly one million instructions executed later, a perfectly good and valid section of code will behave in absurd ways.

The C++ language has been designed around the idea that performance is extremely important and that programmers make no mistakes; therefore the runtime doesn't waste time checking if array indexes are correct (what's the point if the programmers never use invalid ones? it's just a waste of time).

If you write outside of an array what normally happens is that you're overwriting other things in bad ways, possibly breaking complex data structures containing pointers or other indexes that later will trigger strange behaviors. This in turn will get more code to do even crazier things and finally, some code will do something that is so bad that even the OS (that doesn't know what the program wants to do) can tell the operation is nonsense (for example because you're trying to write outside the whole address space that was given to the process) and kills your program (segfault).

Inspecting where the segfault is coming from unfortunately will only reveal what was the last victim in which the code is correct but that was using a data structure that was corrupted by others, not the first offender.

Just don't make mistakes, ok? :-)