On Tue, Nov 05, 2024 at 08:15:04PM +0300, Alexander Monakov wrote:
> 
> On Tue, 5 Nov 2024, Jakub Jelinek wrote:
> 
> > On Tue, Nov 05, 2024 at 04:47:20PM +0100, Jan Hubicka wrote:
> > > > POSIX semantics for malloc involve errno.
> > > 
> > > So if I can check errno to see if malloc failed, I guess even our
> > > current behaviour of optimizing away paired malloc+free calls provided
> > > that the return value is unused is problematic under POSIX same way as
> > > the proposed patch.
> > 
> > I think the unconditional malloc+free case is fine.
> > errno may be randomly modified by any function which doesn't fail, except
> > for a few special cases (like atoi etc.).
> 
> Not quite randomly: it is never reset back to zero by POSIX functions, and...

Sure, but if we don't call that malloc at all, we don't set it to zero by
doing so.

> > So, one can't really rely on a specific value in errno after a malloc/free
> > pair unless one actually checks the return value of malloc and relies on
> > errno only if it returned NULL.
> > Unless it is something where one relies that the malloc must have definitely
> > failed and in code in between the malloc and free saves the errno value
> > (because after free it is certainly undefined again).
> 
> free is not allowed to modify errno if passed a valid argument:
> 
>   [CX] The free() function shall not modify errno if ptr is a null pointer
>   or a pointer previously returned as if by malloc() and not yet deallocated.
> 
>   https://pubs.opengroup.org/onlinepubs/9799919799/functions/free.html

Missed that.
Anyway, IMHO just checking errno because you rely on malloc must have failed
in certain case is obscure.  You'd better at least that that it actually
failed.

        Jakub

Reply via email to