Write a program that defines an array of type integer Print

Write a program that defines an array of type integer. Print out the array elements and go deliberately *beyond* the end of the array, i.e. read/output array elements with indexes that are not accommodated by the array definition. Now extend your program to continuously write beyond the end of the array Output the induces of the elements that you wrote and check, how many elements you can get away with writing at illegimate locations. What are your conclusions of what you see?

Solution

Following is the code:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void doItFor( long long int sizeOfArray ){
   long long int array[ sizeOfArray ];
   //let us define its elements randomly between 0-9
   srand( time(NULL) );
   for(long long int i = 0; i < sizeOfArray; i++){   array[i] = rand()%10;   }
   //prlong long int the elements
   /*for(long long int i = 0; i < sizeOfArray; i++){
       cout << array[i] << \" \";   
   } cout << endl;
*/
   //time to go beyond the array
   long long int writeAt = sizeOfArray - 1;
   while(true){
           writeAt+= 10;
           cout << \"Array Size is : \" << sizeOfArray << endl;
           cout << \"Writing at index: \" << writeAt << endl;
           array[ writeAt ] = rand()%10;
           cout << \"Wrote at index: \" << writeAt << endl;
           cout << \"Successfully wrote in \"<< writeAt-sizeOfArray+1 << \" illegimate locations\" << endl;
   }

}

int main(){
   doItFor( 1000 );
}

Conclusions:

We can write at illegimate locations, not always though. As we increase the index, we get the segmentation fault, when we try to write on location we are not authorized to write at, as user. Now, additional elements that we can write illegitimately, decreases on average as we increase the size of array. This can be verified by finding out averages and comparing, though one intuition can be that, total memory locations being fixed, bigger the allocated array is, more is the probability that we will reach \'segmentation fault\' causing locations sooner.

 Write a program that defines an array of type integer. Print out the array elements and go deliberately *beyond* the end of the array, i.e. read/output array e

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site