gpt4 book ai didi

c - 取malloc()、realloc()和free()的地址是否可移植?

转载 作者:行者123 更新时间:2023-12-04 04:30:24 24 4
gpt4 key购买 nike

按照标准,取地址malloc()安全吗? , realloc() , 和 free() ?
例如,

#include <stdlib.h>
void * (*my_malloc)(size_t) = &malloc;
推论,在符合标准的 C 中,实现是否可能使用宏用于 malloc/ realloc/ free ?

最佳答案

是的,这是安全的。标准库可以为它的任何函数定义类似函数的宏,但它们也必须作为函数可用。
C17 7.1.4 (1)

Anyfunction declared in a header may be additionally implemented as a function-like macro definedin the header, so if a library function is declared explicitly when its header is included, one of thetechniques shown below can be used to ensure the declaration is not affected by such a macro. Anymacro definition of a function can be suppressed locally by enclosing the name of the function inparentheses, because the name is then not followed by the left parenthesis that indicates expansion ofa macro function name. For the same syntactic reason, it is permitted to take the address of a libraryfunction even if it is also defined as a macro. [189]


[189] This means that an implementation shall provide an actual function for each library function, even if it also provides amacro for that function.


简而言之,库的标题允许具有类似的内容
void *malloc(size_t);
#define malloc(s) __fancy_internal_malloc((s) + 47 | 0x14 * 3)
然后你可以做任何
void *p = malloc(10); // invokes the macro if there is one
void *q = (malloc)(10); // definitely calls the function, not the macro
void *(*allocator)(size_t) = &malloc; // takes address of the function
#undef malloc
void *r = malloc(10); // definitely the function
当然,函数和宏都必须提供标准 promise 的任何行为(尽管正如 Eric Postpischil 评论的那样,只要每个人都符合要求,它们的行为就不必相同)。特别是,用宏分配和用函数释放必须是安全的,反之亦然。此外,这样的宏必须对它的每个参数只计算一次,所以 p = malloc(s++);对于函数或宏来说都是安全的。

关于c - 取malloc()、realloc()和free()的地址是否可移植?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65639693/

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