加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

关于使用malloc()和free()的问题

发布时间:2020-12-16 10:49:40 所属栏目:百科 来源:网络整理
导读:谢谢你注意我的问题. 在C Primer Plus中,它首先写道 The argument to free() should be a pointer to a block of memory allocated by malloc() ; you can’t use free() to free memory allocated by other means 这意味着一个malloc(),ONE和一个free(). 但
谢谢你注意我的问题.

在C Primer Plus中,它首先写道

The argument to free() should be a pointer to a block of memory allocated by malloc(); you can’t use free() to free memory allocated by other means

这意味着一个malloc(),ONE和一个free().

但是后来它会发生

It’s okay to use a different pointer variable with free() than with malloc(); what must agree are the addresses stored in the pointers.

这似乎与第一个陈述相矛盾.

所以我的理解是,只要一对malloc()和free()共享相同的地址就没有错误,并且指针的名称无关紧要.我对吗?

解决方法

例如:

void* p = malloc (100);
void* q = p;
free (q);

……很好. free()的参数是malloc返回的值.这句话

“It’s okay to use a different pointer variable with free() than with
malloc()”

实际上是没有意义的,只会产生混淆 – 当然只要值相同就可以使用不同的变量.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读