Is %p specifier only for valid pointers?

前端 未结 4 1397
失恋的感觉
失恋的感觉 2021-02-12 12:47

Suppose on my platform sizeof(int)==sizeof(void*) and I have this code:

printf( \"%p\", rand() );

Will this be undefined behavior

4条回答
  •  暖寄归人
    2021-02-12 13:32

    C standard, 7.21.6.1, The fprintf function, states just

    p The argument shall be a pointer to void.

    By Appendix J.2, this is a constraint, and violating a constraint causes UB.

    (Below is my previous reasoning why this should be UB, which was too complicated.)

    That paragraph does not describe how the void* is retrieved from the ..., but the only way that the C standard itself offers for this purpose is 7.16.1.1, The va_arg macro, which warns us that

    if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined

    If you read 6.2.7, Compatible type and composite type, then there's no hint that void* and int should be compatible, regardless of their size. So, I'd say that since va_arg is the only way to implement printf in standard C, the behavior is undefined.

提交回复
热议问题