`free()` 包装器

发布于 2024-10-31 07:05:04 字数 764 浏览 3 评论 0原文

我正在尝试编写 mallocfree 包装器,我想知道为什么下面的代码会给出错误 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ㄖ落Θ余辉 2024-11-07 07:05:04

既然是你,

int *p;
p = new(1, int);
delete(&p);

那么你就应该

void delete(int** ptr) //two ** here!!
{
    free(*ptr);
    *ptr = NULL;
}

Since you,

int *p;
p = new(1, int);
delete(&p);

Then you should

void delete(int** ptr) //two ** here!!
{
    free(*ptr);
    *ptr = NULL;
}
转角预定愛 2024-11-07 07:05:04

您正在free()指针所指向的对象(*ptr),而不是指针ptr本身。< /罢工>
错过了 delete() 调用中的 &;对不起。

You're free()ing the thing the pointer is pointing to (*ptr), not the pointer ptr itself.
Missed the & in the delete() call; sorry.

随波逐流 2024-11-07 07:05:04

问题是这一行

free(*ptr);

The free function is Expecting a pointer value but you're Give it an int 相反。试试这个

free(ptr);

编辑

为什么投反对票? delete 函数对于 free 的使用来说是完全错误的,我关于它的陈述是正确的。事实上,delete 的具体错误用法使其一切正常(其正确性取决于平台),但这并不意味着我的答案不正确。

The problem is this line

free(*ptr);

The free function is expecting a pointer value but you're giving it an int instead. Try this

free(ptr);

EDIT

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 of delete makes it all kinda work (it's correctness is platform dependent) doesn't make my answer incorrect.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文