←back to thread

48 points ingve | 1 comments | | HN request time: 0.204s | source
Show context
AaronDinesh ◴[] No.44389347[source]
Why should it be allowed to return a valid pointers anyways? Surely it should always return NULL?
replies(5): >>44389371 #>>44389461 #>>44389531 #>>44390081 #>>44392719 #
cjensen ◴[] No.44389531[source]
There are three reasonable choices: (a) return the null pointer (b) return a valid unique pointer and (c) abort().

The point of the original C Standard was to make rules about these things AND not break existing implementations. They recognized that (a) and (b) were in existing implementations and were reasonable, and they chose not to break the existing implementations when writing the standard.

This is similar to the extremely unfortunate definition of the NULL macro. There were two existing styles of implementation (bare literal 0 and (void *) 0) and the Standard allows either style. Which means the NULL macro is not entirely safe to use in portable code.

replies(1): >>44389592 #
commandlinefan ◴[] No.44389592[source]
> return a valid unique pointer

A pointer to what, though? If the requester asked for 0 bytes of memory, you'd either be pointing to memory allocated for another purpose (!) or allocating a few bytes that weren't asked for.

> This makes people unhappy for various reasons

I read through all the links trying to figure out what those reasons might be and came up empty, I'm still curious why anybody would expect or rely on anything except a null pointer in this instance.

replies(4): >>44389671 #>>44389719 #>>44389745 #>>44389786 #
DSMan195276 ◴[] No.44389719[source]
> allocating a few bytes that weren't asked for.

FWIW the alignment guarantees of `malloc()` mean it often will have to allocate more than you ask for (before C23 anyway). You can't 'legally' use this space, but `malloc()` also can't repurpose it for other allocations because it's not suitably aligned.

That said I still agree it's a hack compared to just using `malloc(1)` for this purpose, it's well-defined and functionally equivalent if you're looking for a unique address. The fact that you don't know what `malloc(0)` is going to do makes it pretty useless anyway.

replies(1): >>44390146 #
Joker_vD ◴[] No.44390146[source]
> before C23 anyway

Did they change "suitably aligned for any object type" to "suitably aligned for any object type with size less than or equal to what was requested" or something like in C23?

replies(1): >>44390622 #