C / C ++:取消分配或删除动态创建的内存块 [英] C/C++ : Deallocating or deleting a block of dynamically created memory

查看:164
本文介绍了C / C ++:取消分配或删除动态创建的内存块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1930459/c-delete-it-deletes-my-objects-but-i-can-still-access-the-data\">C++删除 - 它删除我的对象,但我仍然可以访问数据

我试图释放在C / C动态创建的内存++块。
但无论我用标准方法(的malloc /免费新/删除)似乎是不正常的。

下面给出的O /无论是codeS的p是相似的。

下面是使用code的malloc /免费:

I am trying to deallocate a block of dynamically created memory in C/C++.
But both the standard methods I used (malloc/free and new/delete) seems to be dysfunctional.
The o/p of both the codes given below is similar.
Here is code using 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");
    }


这里是code。使用新的/删除[]:


Here is code using 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");
    }

但是,即使重新分配内存后,他们都不是给任何错误。

在这两种情况下的O / P是相同的:

But, even after deallocating the memory, none of them are giving any errors.
The o/p in both the cases is same :

0 1 2 3 4 5 6 7 8 9
0 0 2 3 4 5 6 7 8 9


那么,什么是C / C释放内存的正确的方法+ +?另外,为什么在数组是越来越甚至重新分配内存之后打印?


So, what is the correct method of deallocating memory in C/C++ ? Also, why is the array is getting printed even after deallocating the memory ?

推荐答案

由于取消分配/释放内存并不意味着的被取消的的或这样的事情。

Because deallocating/freeing memory does not mean annulling or something like this.

释放内存(最有可能)会刚刚庆祝了一块内存免费,不会做别的事吧,直到别的东西再次使用它。

Freeing memory (most likely) will just mark that piece of memory as free and will not do anything else to it, until something else use it again.

这使得释放内存速度更快。

This makes the freeing memory faster.

您在code有什么的未定义行为的,因为你正在阅读(使用)的内存,那你不应该在所有触摸。它的释放,并使用该内存可能导致任何东西。在最好的情况下崩溃。

What you have in your code is undefined behaviour, because you're reading (using) memory, that you're not supposed to touch at all. It's "freed" and using that memory could cause anything. A crash in the best case.

这篇关于C / C ++:取消分配或删除动态创建的内存块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆