本文介绍了C ++数组:为什么delete []不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行以下代码时:

#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]) << " ";
    }

结果是:

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

因此,问题是delete[]没有删除整个数组.如果我创建一个整数数组,则删除的插槽数为2.我在Arch Linux下使用的是g ++/gcc 4.9.

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?

顺便说一句:已删除"数组中"0"的数目似乎等于:

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

sizeof(TestArray)/sizeof(TestArray[0])

推荐答案

删除内存后,您正在访问内存.这会引起未定义的行为.可能存在运行时错误,也可能没有.

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.

这篇关于C ++数组:为什么delete []不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:53