如果我再alloc和新的大小为0这相当于一个免费的,会发生什么? [英] What happens if I re-alloc and the new size is 0. Is this equivalent with a free?

查看:144
本文介绍了如果我再alloc和新的大小为0这相当于一个免费的,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下code:

int *a = NULL;
a = calloc(1, sizeof(*a));
printf("%d\n", a);
a = realloc(a, 0);

printf("%d\n", a);
return (0);

返回的是:

4078904
0

这是realloc的相当于一个免费的吗?

Is this realloc equivalent to a free ?

请注意:
我使用的是WindowsXP下的MinGW。

NOTE: I am using MinGW under WindowsXP.

推荐答案

不一定。

这经常做与该<一个href=\"http://stackoverflow.com/questions/2546572/what-happens-if-i-re-alloc-and-the-new-size-is-0-is-this-equivalent-with-a-free/2546580#2546580\">link这munissor发布,但在Mac OS 10.5手册页说:

It often does as with the link that munissor posted, but the Mac OS 10.5 man page says:

如果大小为零而ptr不是NULL,一个新的,最小的大小的对象被分配和原始对象被释放

If size is zero and ptr is not NULL, a new, minimum sized object is allocated and the original object is freed.

什么是最小尺寸对象?那么,任何分配存储有关分配的一些信息,而这需要这往往是除了为用户保留的空间分配的空间。 presumably最小大小的对象,只是这些头加上零字节的空间,为用户预留之一。

What is a "minimum sized object"? Well, any allocator stores some information about the allocations, and that takes space which is often allotted in addition to the space reserved for the user. Presumably a "minimum sized object" is just one of these headers plus zero bytes of space reserved for the user.

我猜想,这一规定是present支持,在标准化存在的时候实现,而这些实现对于调试分配行为很有用的。

I would guess that this provision is present to support implementations that existed at the time of standardization, and that those implementations are useful for debugging allocation behavior.

要解决<一个href=\"http://stackoverflow.com/questions/2546572/what-happens-if-i-re-alloc-and-the-new-size-is-0-is-this-equivalent-with-a-free/2546762#2546762\">Jonathan's评论

考虑

for (int i=0; i<VERY_BIG_NUMBER; ++i){
  char *p = malloc(sizeof(char[10]));
  free(p);
}

for (int i=0; i<VERY_BIG_NUMBER; ++i){
  char *p = malloc(sizeof(char[10]));
  realloc(p,0);
}

通过一个健全的实施的malloc 免费第一个剪辑做的的消耗内存无限制。但是,如果的realloc 实现返回那些最小尺寸的物体可能。

With a sane implementation of malloc and free the first clip does not consume memory without bound. But if the realloc implementation returns those "minimum sized objects" it might.

当然,这种例子是人为的,它依赖于理解什么是最小尺寸对象的意思,但我认为,文本允许它。

Certainly this example is contrived and it relies on understanding what is meant by "minimum sized object", but I think that text allows it.

在总之,如果你的的意思是免费你应该说免费

In short, if you mean free you should say free.

这篇关于如果我再alloc和新的大小为0这相当于一个免费的,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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