乐闻世界logo
搜索文章和话题

Printing null pointers with %p is undefined behavior?

1个答案

1

In C programming, using the %p format specifier to print pointers is the standard practice for outputting the address of a pointer variable. According to the C language standard (e.g., ISO/IEC 9899), when using the printf function with the %p format specifier to print a pointer, a void* pointer must be passed.

Regarding null pointers (typically defined as NULL), the standard specifies that a void* pointer should be passed when using %p for printing. Although NULL represents an invalid address, using %p to print it is well-defined behavior. Typically, printing a NULL pointer yields results such as (nil) or 0x0, depending on the specific implementation and platform.

Example: The following code snippet demonstrates how to safely print a null pointer in a C program:

c
#include <stdio.h> int main() { void *ptr = NULL; printf("Pointer address: %p\n", ptr); return 0; }

In this example, ptr is a null pointer initialized to NULL. When printed using %p, the output is expected to be either (nil) or 0x0, depending entirely on the compiler and runtime platform implementation.

To summarize, using %p to print a null pointer in C is well-defined and legal behavior, not causing undefined behavior. However, developers should ensure that the correct type (void*) is passed during printing to avoid potential type mismatch issues.

2024年6月29日 12:07 回复

你的答案