C++ Array: why is delete[] not working? [duplicate]

佐手、 提交于 2019-12-20 07:52:41

问题


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])

回答1:


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.



来源:https://stackoverflow.com/questions/23461434/c-array-why-is-delete-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!