Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [<thread-prev] [day] [month] [year] [list]
Message-ID: <acHnnsjm3ngvwfnr@devuan>
Date: Tue, 24 Mar 2026 02:26:24 +0100
From: Alejandro Colomar <une+c@...jandro-colomar.es>
To: Charles Munger <clm@...gle.com>
Cc: sc22wg14@...n-std.org, Rich Felker <dalias@...c.org>, 
	musl@...ts.openwall.com
Subject: Re: [SC22WG14.35974] N3849 - Memory allocation with size feedback
 v2, request for feedback

Hi Charles,

On 2026-03-23T17:58:55-0700, Charles Munger wrote:
> On Thu, Mar 19, 2026 at 4:16 PM Alejandro Colomar <une+c@...jandro-colomar.es> wrote:
> > |       As far as developer ergonomics,
> > |       there are costs and benefits to each approach.
> > |       The functions that return a pointer
> > |       (and use an out-param for the size)
> > |       can assign the return value directly
> > |       to where it’s likely to be consumed,
> > |       to a non-`void` pointer.
> >
> > This is what makes it importantly safer.
> >
> >         alx@...uan:~/tmp$ cat m.c
> >         #include <stdlib.h>
> >
> >         #define typeas(T)          typeof((T){})
> >         #define mallocarray(n, z)  reallocarray(NULL, (n)?:1, z)
> >         #define malloc_T(n, T)     malloc_T_(n, typeas(T))
> >         #define malloc_T_(n, T)    ((void)0, (T *){mallocarray(n,
> > sizeof(T))})
> >
> >         int
> >         main(void)
> >         {
> >                 long *p;
> >
> >                 p = malloc_T(42, long);  // ok
> >                 free(p);
> >
> >                 p = malloc_T(42, int);   // -Wincompatible-pointer-types
> >                 free(p);
> >         }
> >         alx@...uan:~/tmp$ gcc m.c
> >         m.c: In function ‘main’:
> >         m.c:16:11: error: assignment to ‘long int *’ from incompatible
> > pointer type ‘int *’ [-Wincompatible-pointer-types]
> >            16 |         p = malloc_T(42, int);   //
> > -Wincompatible-pointer-types
> >               |           ^
> >
> > Your variant is inherently unsafe, and can't be made type-safe in any
> > way.  This is a non-starter, IMO.
> >
> If you're going to wrap it that way you can wrap it in a `static
> inline` function that uses any of the alternative structures you prefer,
> which would then permit this same macro for typing.

You'd need to have a different struct+function pair of wrappers for each
different type you need to allocate.  My type-generic macro works for
all malloc(3) calls, so you only need to write it once.


Have a lovely night!
Alex

-- 
<https://www.alejandro-colomar.es>

Download attachment "signature.asc" of type "application/pgp-signature" (834 bytes)

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.