释放分配的指针 [英] Free an assigned pointer

查看:62
本文介绍了释放分配的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是否释放为 x 分配的内存?

Does the following code free the memory that was allocated for x?

int main()
{
    char *x = (char*)calloc(100, sizeof(char));
    char *y = x;
    free(y);
}

推荐答案

这样做的时候

char *y = x;

您将 y 指向 x 指向的位置.由于 y 指向 calloc 返回的内存位置,因此

you make y point to the location where x points to. Since y points to a memory location returned by calloc,

free(y);

是完全有效的.作为 @haccks

is perfectly valid. As @haccks commented, this would not work if you make y point to another memory location, provided that this memory location wasn't returned by malloc/calloc/realloc.

在C语言中,不应该转换 malloc / calloc / realloc .同样,检查 calloc 的返回值以查看是否成功. calloc 将在失败时返回 NULL .

In C, you should not cast the result of malloc/calloc/realloc. Also, checking the return value of calloc to see if it was successful is good. calloc will return NULL on failure.

这篇关于释放分配的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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