-2

I answered a question, If you use wrong format specifier then the behaviour of your code is undefined.

In that question, OP used %lu format specifier for sizeof operator.

printf("%lu \n", sizeof(*"327")); 

But, I got some comments, %lu not UB for that code.

So, Is it true for sizeof(*"327")?

9
  • The discussion in the comments seemed to be about whether size_t is typedefd to be unsigned long or not, so whether it invokes UB or not seems to depend on the compiler? Commented Oct 13, 2017 at 12:16
  • Well, I think the bigger problem is, "Why would you ever do that." There's nothing really "wrong" with the format specifier, though that may not be the specifier that will properly display the value.. That simply means that it will be displayed incorrectly, not that it is necessarily UB. Commented Oct 13, 2017 at 12:18
  • @Jens Gustedt Actually sir I know correct format specifier of sizeof. And also I mentioned in my answer , but some peoples commented my answer, it's not UB?? My answer : stackoverflow.com/a/46705515/6935629 Commented Oct 13, 2017 at 12:27
  • @rsp, reopened. But this was not at all clear from your question, please improve it. The contents should not be hidden behind links. Commented Oct 13, 2017 at 12:47
  • 1
    @SouravGhosh, so what you found is again wrong, it does not answer the question that rsp wanted to ask. Commented Oct 13, 2017 at 12:53

2 Answers 2

1

The sizeof operator returns a type of size_t. The proper format specifier for that type is %zu.

If you use %lu to print a size_t, it may or may not work, depending on whether or not size_t is larger than a long. If size_t is larger, you have undefined behavior, if not the behavior is well defined. Of course, you can't really know for sure.

Better to use the proper format specifier specific to that type.

Sign up to request clarification or add additional context in comments.

Comments

1

Unix systems (nearly?) always have size_t == unsigned long == uintptr_t, and there is a lot of code that relies on the fact.

The only system in common use that's different is 64-bit Windows, where unsigned long is 32-bit but size_t and uintptr_t are 64-bit.

(Does windows even have a support for %zu in printf?)

1 Comment

"Does windows even have a support %zu ..." that not a question of the OS, but of the compiler. VC hasn't, others have.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.