Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: [PATCH] mem: Align heap allocations for pointers too



Florian Schmaus wrote on Mon, 23 Nov 2026 15:51 +00:00:
> Add a void * member to union mem_align, so that heap allocations are
> suitably aligned for pointers too.

First, the comment on line 1030 will need to be updated:

    Memory is given in blocks aligned to an integer multiple of
    sizeof(union mem_align), which will probably be 64-bit as it is the
    longer of zlong or double.

Secondly, if I understand correctly, mem_align is what determines the
alignment of zhalloc()'s return value.  If so, are we guaranteed that
alignment that's sufficient for zlong, for double, and for a pointer
would be sufficient, on all platforms, for any type we might use?
I assume we should align as much as malloc(3) does.

Per cppreference [1] [2], malloc(3) aligns to multiples of max_align_t,
which is new in C11.

Should we align to max_align_t as well (conditionally on being supported
by the compiler/libc, of course)?

[1] https://en.cppreference.com/c/memory/malloc
[2] https://en.cppreference.com/c/language/object#Alignment

> This also raises the block alignment (M_ALIGN) of the optional ZSH_MEM
> allocator accordingly.

If I'm not mistaken, the incumbent code assumes that M_ALIGN is a power
of 2 (when it does «(size + M_ALIGN - 1) & ~(M_ALIGN - 1)» — that's
"round up to the next multiple of M_ALIGN" when M_ALIGN is a power
of 2), but nothing guarantees that to be the case.

This /is/ a preëxisting issue, but it's not unrelated to the patch,
unfortunately: it does bear on whether the patch might introduce
a regression on some platforms.

Cheers,

Daniel

> 1: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
> 2: https://codasip.com/solutions/riscv-processor-safety-security/cheri/
> ---
>  Src/mem.c | 1 +
>  1 file changed, 1 insertion(+)
>
> diff --git a/Src/mem.c b/Src/mem.c
> index 0b6f76e46b2b..5d9ba7d280a5 100644
> --- a/Src/mem.c
> +++ b/Src/mem.c
> @@ -113,6 +113,7 @@ static int h_m[1025], h_push, h_pop, h_free;
>  union mem_align {
>      zlong l;
>      double d;
> +    void *p;
>  };
> 
>  #define H_ISIZE  sizeof(union mem_align)
> -- 
> 2.56.1




Messages sorted by: Reverse Date, Date, Thread, Author