我正在尝试编写malloc和free包装器,我想知道为什么下面的代码会给出错误的pointer being freed was not allocated,为什么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);
}发布于 2011-04-07 06:26:35
既然是你,
int *p;
p = new(1, int);
delete(&p);那么你应该
void delete(int** ptr) //two ** here!!
{
free(*ptr);
*ptr = NULL;
}发布于 2011-04-07 06:25:16
问题是这一行
free(*ptr);free函数需要一个指针值,但是您给了它一个int。尝尝这个
free(ptr);编辑
为什么要投反对票?delete函数在空闲的用法方面是完全不正确的,我关于它的陈述是正确的。事实上,delete的特定不正确用法使它完全正常工作(它的正确性取决于平台),但这并不会使我的答案不正确。
https://stackoverflow.com/questions/5573703
复制相似问题