Re:Tell HN: C Experts Panel – Ask us anything about C
by dhhwrongagain on Tuesday April 14, 2020 @03:43PM
(#22870548)
Is memset(malloc(0), 0, 0) undefined behavior?
[ Parent
| on HN ]
Re:Tell HN: C Experts Panel – Ask us anything about C
by DougGwyn on Tuesday April 14, 2020 @04:43PM
(#22871183)
Let's assume the types have been corrected.
malloc((size_t)0) behavior is defined by the implementation; there are two choices: (a) always returns a null pointer; or (b) acts like malloc((size_t)1) which can allocate or fail, and if it allocates then the program shall not try to reference anything through the returned non-null pointer.
Now, memset itself is required (among other things) to be given as its first argument a valid pointer to a byte array. In particular, it shall not be a null pointer. Tracking through the conformance requirements, if the malloc call returns a null pointer then the behavior is undefined. Thus, you should not program like this.
Re:Tell HN: C Experts Panel – Ask us anything about C
by dhhwrongagain on Wednesday April 15, 2020 @05:06AM
(#22875827)
What observable difference is there between malloc(0) and malloc((size_t)0)?
Re:Tell HN: C Experts Panel – Ask us anything about C
by saagarjha on Wednesday April 15, 2020 @05:07AM
(#22875830)
None.
Re:Tell HN: C Experts Panel – Ask us anything about C
by dhhwrongagain on Wednesday April 15, 2020 @05:16AM
(#22875865)
I agree but he said the types needed to be corrected. As far as I know the types were already correct.
Re:Tell HN: C Experts Panel – Ask us anything about C
by DougGwyn on Thursday April 16, 2020 @07:21PM
(#22894589)
The argument "0" is not automatically converted to the right type unless there is a prototype in scope. It isn't as important in this case because it is highly likely that the appropriate prototype has been #included, but it is a bigger deal if we're dealing with arguments for a variadic function. Anyway, it's good to be reminded what the declared types are.
Re:Tell HN: C Experts Panel – Ask us anything about C
by dhhwrongagain on Tuesday April 21, 2020 @11:04AM
(#22935523)
Are you serious? Of course the question comes with the reasonable assumption that the proper declaration has been made especially since it’s a well known standard function. Additionally memset() is not a variadic function.
You said the types were corrected, you didn’t say you were reminding about the declaration types. The types were correct from the start.