标题几乎说明了一切,但我会重申问题...
下面的程序是不是C99标准下的“严格符合程序”?
#include <stdlib.h>
/* Removing any pre-existing macro definition, in case one should exist in the implementation.
* Seems to be allowed under 7.1.3 para 3, as malloc does not begin with _X where X is any capital letter.
* And 7.1.4 para 1 explicitly permits #undef of such macros.
*/
#ifdef malloc
#undef malloc
#endif
/* Macro substitution has no impact on the external name malloc
* which remains accessible, e.g., via "(malloc)(s)". Such use of
* macro substitution seems enabled by 7.1.4 para 1, but not specifically
* mentioned otherwise.
*/
void * journalling_malloc(size_t size);
#define malloc(s) ((journalling_malloc)(s))
int main(void)
{
return malloc(10) == NULL ? 1 : 0;
/* Just for the sake of expanding the
* macro one time, return as exit code
* whether the allocation was performed.
*/
}
最佳答案
让我们看看 C99 标准是怎么说的:
参见 7.1.3,§1,第 5 条:
Each identifier with file scope listed in any of the following subclauses [...] is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.
当您包含 stdlib.h
时,名称 malloc
被保留用作宏名称。
但是 7.1.4,§1 允许在保留名称上使用 #undef
:
The use of
#undef
to remove any macro definition will also ensure that an actual function is referred to.
这使得重新#define
malloc
成为可能,根据 7.1.3,§2,这会导致未定义的行为:
If the program [...] defines a reserved identifier as a macro name, the behavior is undefined.
标准为什么做这个限制?因为标准库的其他函数可能会根据原始函数实现为类似函数的宏,因此隐藏声明可能会破坏这些其他函数。
在实践中,只要您对 malloc
的定义满足标准为库函数提供的所有规定,您就应该没问题,这可以通过包装对 malloc( )
。
关于c - 以下程序是否严格符合 C99 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2268149/