使用realloc/malloc免费实现 [英] Implement free using realloc/malloc

查看:72
本文介绍了使用realloc/malloc免费实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用零大小的malloc/realloc密码来实现免费吗?

在以下代码块中,重新分配功能是否与free功能相同?

Can we implement free using malloc/realloc passig size zero to them?

In the following code blocks does realloc functions same as free?

int *x = NULL;
x = (int*)malloc(7*sizeof(int));
memset(x,0,7);
printf("%u  %u  %d\n",&x, x,*x);
free(x);







int *x = NULL;
x = (int*)malloc(7*sizeof(int));
memset(x,0,7);
printf("%u  %u  %d\n",&x, x,*x);

x = (int*)realloc(x,0*sizeof(int));
printf("%u  %u\n",&x, x);

推荐答案

不一定-零长度的块与已发布的块不同,它具有有效地址,并且(可能)占用该块上的空间/under运行检查和分配表中.一个智能系统可能会检测到零长度,因为它重复使用了相同的零长度块,但是如果原始编码器认为不值得在所有非零块上花费时间,那么它就没有必要,也可能不会.
Not necessarily - a zero length block is not the same as a released block, it has a valid address and (probably) takes up space both for the block over/under run checking and in the allocation tables. An intelligent system might detect the zero length as re-use the same zero length block, but it doesn''t have to and may not if the original coder didn''t think it worth the time overhead on all non-zero blocks (i.e. nearly all of them) to do the checks.


好吧,C ++标准中允许有许多奇怪的条件. http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/ [ ^ ]
但我不建议采用它们作为编码风格.

例如,允许您释放()一个NULL指针.

您可以realloc()一个NULL指针,然后realloc()然后充当malloc()

您可以将realloc()设置为非NULL指针,但将大小指定为0,以便realloc()然后用作free()

它们是允许的,但是如果您决定使用这些怪癖而不是对通常的库函数进行合理的调用,最终将给以后尝试遵循/修改您的代码的任何人带来很多问题.

技巧是给孩子的"(tm)真正的程序员编写了可读且可维护的代码.
Well, there are many strange conditions allowed for in the C++ standard. http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/[^]
but I wouldn''t recommend adopting them as a coding style.

For example, you are allowed to free() a NULL pointer.

You can realloc() a NULL pointer and realloc() then acts as malloc()

You can realloc() a non-NULL pointer but specify the size as 0 so realloc() then acts as free()

They are allowed but if you decide to use those quirks instead of making reasonable calls to the usually library functions, you will end up causing lots of problems for anyone who tries to follow / modify your code in the future.

"Tricks are for Kids" (tm) Real Programmers write readable and maintainable code.


这篇关于使用realloc/malloc免费实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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