`free()` 包装器
我正在尝试编写 malloc
和 free
包装器,我想知道为什么下面的代码会给出错误 pointer being freed was not allocate
,为什么delete()
不起作用吗?
#include <stdio.h>
#include <stdlib.h>
#define log(v) printf(#v " == %d \n", v)
#define new(n, type) _new((n), sizeof(type), __LINE__, __FILE__)
void *_new(int n, size_t size, int line, char *file)
{
int *ptr;
ptr = malloc(n * size);
if (ptr == NULL)
{
printf("new(): Memory allocation error, file \"%s\", line %d. \n", file, line);
exit(EXIT_FAILURE);
}
return ptr;
}
void delete(int *ptr)
{
free(*ptr);
*ptr = NULL;
}
main()
{
int *p;
p = new(1, int);
log(p);
delete(&p);
log(p);
}
I'm experimenting with writing malloc
and free
wrappers, and I wonder why does the following code gives error pointer being freed was not allocated
, why does not delete()
work?
#include <stdio.h>
#include <stdlib.h>
#define log(v) printf(#v " == %d \n", v)
#define new(n, type) _new((n), sizeof(type), __LINE__, __FILE__)
void *_new(int n, size_t size, int line, char *file)
{
int *ptr;
ptr = malloc(n * size);
if (ptr == NULL)
{
printf("new(): Memory allocation error, file \"%s\", line %d. \n", file, line);
exit(EXIT_FAILURE);
}
return ptr;
}
void delete(int *ptr)
{
free(*ptr);
*ptr = NULL;
}
main()
{
int *p;
p = new(1, int);
log(p);
delete(&p);
log(p);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
既然是你,
那么你就应该
Since you,
Then you should
您正在free()
指针所指向的对象(*ptr
),而不是指针ptr
本身。< /罢工>错过了
delete()
调用中的&
;对不起。You'refree()
ing the thing the pointer is pointing to (*ptr
), not the pointerptr
itself.Missed the
&
in thedelete()
call; sorry.问题是这一行
The
free
function is Expecting a pointer value but you're Give it anint
相反。试试这个编辑
为什么投反对票?
delete
函数对于 free 的使用来说是完全错误的,我关于它的陈述是正确的。事实上,delete
的具体错误用法使其一切正常(其正确性取决于平台),但这并不意味着我的答案不正确。The problem is this line
The
free
function is expecting a pointer value but you're giving it anint
instead. Try thisEDIT
Why the downvotes? The
delete
function is flat out incorrect with respect to the usage of free and my statements about it are correct. The fact that the specific incorrect usage ofdelete
makes it all kinda work (it's correctness is platform dependent) doesn't make my answer incorrect.