C/C++:取消分配或删除动态创建的内存块

c_s*_*rma 2 c c++ pointers dynamic-memory-allocation

可能重复:
C++删除 - 删除我的对象,但我仍然可以访问数据?

我试图在C/C++中释放一块动态创建的内存.
但是我使用的标准方法(malloc/free和new/delete)似乎都是功能失调的.
下面给出的两个代码的o/p是相似的.
这是使用malloc/free的代码:

    #include<stdio.h>
    #include<stdlib.h>

    int main(){
        int * arr;
        arr = (int *)malloc(10*sizeof(int)); // allocating memory
        int i;
        for(i=0;i<10;i++)
            arr[i] = i;
        for(i=0;i<10;i++)
            printf("%d ",arr[i]);
        printf("\n");
        free(arr); // deallocating
        for(i=0;i<10;i++)
            printf("%d ",arr[i]);
        printf("\n");
    }
Run Code Online (Sandbox Code Playgroud)


这是使用new/delete []的代码:

    #include<stdio.h>
    #include<stdlib.h>

    int main(){
        int * arr;
        arr = new int[10]; // allocating memory
        for(int i=0;i<10;i++)
            arr[i] = i;
        for(int i=0;i<10;i++)
            printf("%d ",arr[i]);
        printf("\n");
        delete[] arr; // deallocating
        for(int i=0;i<10;i++)
            printf("%d ",arr[i]);
        printf("\n");
    }
Run Code Online (Sandbox Code Playgroud)

但是,即使在释放内存之后,它们也没有任何错误.
两种情况下的o/p都是相同的:

0 1 2 3 4 5 6 7 8 9
0 0 2 3 4 5 6 7 8 9
Run Code Online (Sandbox Code Playgroud)


那么,在C/C++中解除内存释放的正确方法是什么?另外,为什么即使在释放存储器后阵列也会被打印出来?

Kir*_*rov 5

因为释放/释放内存并不意味着取消或类似的东西.

释放内存(最有可能)只会将该内存标记为空闲,并且不会对其执行任何其他操作,直到其他内容再次使用它为止.

这使得释放内存更快.

您在代码中拥有的是未定义的行为,因为您正在阅读(使用)内存,而您根本不应该触摸它.它被"释放"并且使用该内存可能会导致任何问题.在最好的情况下崩溃.