gpt4 book ai didi

检查指针是否位于 malloc 区域?

转载 作者:行者123 更新时间:2023-11-30 19:51:39 25 4
gpt4 key购买 nike

我正在制作一个动态内存分配器,当我释放其中的一部分时,我需要检查我传递给函数的指针实际上是否在该区域内。我有一个指向 malloc 区域开头的指针

typedef unsigned char byte;

static byte *memory // pointer to start of allocator memory

我在启动函数中分配的。我还存储了 malloc 区域的大小

static u_int33_t memory_size;   // number of bytes malloc'd in memory[]

如何确保 ptr 不是...(伪代码)

ptr < *memory || ptr > *memory + memory_size

该代码会导致以下错误;

错误:不同指针类型的比较缺少强制转换 [-Werror] if ( 对象 < 内存 || 对象 > (内存 + 内存大小)) ^

我不确定我需要转换什么,不应该转换什么......

免费功能如下...

void memfree(void *object)
{
if ( object < memory || object > (memory + memory_size)) {
fprintf(stderr, "vlad_free: Attempt to free via invalid pointer\n");
exit(EXIT_FAILURE);
}
}

最佳答案

原版

正如 Raymond Chen's answer 所指出的那样,这是错误的

void memfree(void *_object)
{
byte* object = (byte*)_object;
if ( object >= memory && object < (memory + memory_size)) {
/* defined guarantees - they happened to be in the same object. */
} else {
fprintf(stderr, "memfree: Attempt to free via invalid pointer\n");
exit(EXIT_FAILURE);
}
}

指针的类型必须相同。鉴于您似乎有一个以字节为单位的范围,似乎最好使用字节。

来自C标准n1570

When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.

在这里,我相信未定义的行为是,您无法判断在两个系统上是否会有一致的排序,因此使用 a < b 的代码,在某些系统上可能为 true,而在其他系统上可能为 false。

新答案

使用

void memfree(void *_object)
{
uintptr_t object = (uintptr_t)_object;
if ( object >= (uintptr_t)memory && object < ((uintptr_t)memory + (uintptr_t)memory_size)) {
/* defined guarantees - they happened to be in the same object. */
} else {
fprintf(stderr, "memfree: Attempt to free via invalid pointer\n");
exit(EXIT_FAILURE);
}
}

关于检查指针是否位于 malloc 区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39158853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com