Question

When I run the following code:

#include <iostream>
using namespace std;

main(){
  //declare:
    char* TestArray = new char[16];
    for(char i=0; i<16; i++){
            TestArray[i]=rand() % 10;
    }
  //output Array:
    for(char i=0; i<16; i++){
            cout << int(TestArray[i]) << " ";
    }
  //delete it:
    delete[] TestArray;
  //output result:
    for(char i=0; i<16; i++){
            cout << int(TestArray[i]) << " ";
    }

the outcome is:

3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 //declared Array
0 0 0 0 0 0 0 0 9 1 2 7 0 9 3 6 //'deleted' Array

So, the Problem is, that delete[] is not deleting the entire Array. If I make an Array of int, the number of deleted slots is 2. I am using g++/gcc 4.9 under Arch Linux.

What is the reason to that and how will I be able to fix it?

By the way: the number of '0's in the 'deleted' Array seems to be equivalent to:

sizeof(TestArray)/sizeof(TestArray[0])
Was it helpful?

Solution

You are accessing memory after it has been deleted. That invokes undefined behaviour. There may be a runtime error, or maybe not.

All that it means to delete a block of memory is that you are promising not to use that pointer again. The system is thus free to do what it wants with that memory. It may re-use it. It may do nothing with it initially. You promised not to use the pointer again, but then broke that promise. At that point anything can happen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top