user1825608
user1825608

Reputation:

Accessing deleted array- access violation exception

I wanted to access deleted array to see how the memory was changed it works till I deleted really big array then I get access violation exception. Please do not care about cout I know they are slow but I will get rid of them. When I do it for 1000 elements array it is ok, when I do it for 1000000 i get an exception. I know that this is weird task but my teacher is stubborn and I can't find out how to deal with that.

EDIT: I know that I never should access that memory, but I also know that there is probably trick he will show then and tell that I am not right.

    long max = 1000000;// for 10000 i do not get any exception.
    int* t = new int[max];
    cout<<max<<endl;
    uninitialized_fill_n(t, max, 1); 
    delete[] t;
    cout<<"deleted t"<<endl;
    int x;
    cin>>x;//wait little bit
    int one = 1;
    long counter = 0;
        for(long i = 0; i < max; i++){
            cout<<i<<endl;
            if(t[i] != 1){
                cout<<t[i]<<endl;
                counter++;          
            }               
        }

Upvotes: 0

Views: 247

Answers (3)

Marc Claesen
Marc Claesen

Reputation: 17026

Accessing memory that is no longer in use results in undefined behaviour. You will not get any consistent patterns. If the original memory has not been overwritten after it became invalid, the values will be exactly what they used to be.

I find the answer to this similar question to be very clear in explaining the concept with a simple analogy.

A simple way to mimic this behaviour is to create a function which returns a pointer to a local variable, for example:

int *foo(){
 int a=1;
 return &a;
}

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129504

That state of "deleted" memory is undefined, to access memory after delete is UNDEFINED BEHAVIOUR (meaning, the C++ specification allows "anything" to happen when you access such memory - including the appearance of it "working" sometimes, and "not working" sometimes).

You should NEVER access memory that has been deleted, and as shown in your larger array case, it may not work to do so, because the memory may no longer actually be available to your process.

Upvotes: 2

nosleduc
nosleduc

Reputation: 103

You are not allowed to access to a released buffer

Upvotes: 0

Related Questions