1

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])
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
super metty
  • 37
  • 1
  • 3
  • 4
    It is undefined behaviour. you're looking at memory locations you shouldn't. – juanchopanza May 04 '14 at 20:55
  • 1
    delete[] does not necessarily zero the contents of the array you delete. It frees the memory associated with it. You should not try to print the contents of an array after delete[]ing it. For help on "fixing" it you need to explain what you are trying to do. – davmac May 04 '14 at 20:59

1 Answers1

12

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490