https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121786
Bug ID: 121786 Summary: object size expression deduced from alloc_size should have a SIZE_MAX/2 cap Product: gcc Version: 15.1.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: siddhesh at gcc dot gnu.org Target Milestone: --- Consider this example: typedef __SIZE_TYPE__ size_t; void *obj; size_t alloc_and_get_objsz (size_t sz) { obj = __builtin_malloc (sz); return __builtin_dynamic_object_size (obj, 0); } which when built, generates: $ gcc -S -O2 -o - foo.c .file "foo.c" .text .p2align 4 .globl alloc_and_get_objsz .type alloc_and_get_objsz, @function alloc_and_get_objsz: .LFB0: .cfi_startproc pushq %rbx .cfi_def_cfa_offset 16 .cfi_offset 3, -16 movq %rdi, %rbx call malloc movq %rax, obj(%rip) movq %rbx, %rax popq %rbx .cfi_def_cfa_offset 8 ret .cfi_endproc .LFE0: .size alloc_and_get_objsz, .-alloc_and_get_objsz .globl obj .bss .align 8 .type obj, @object .size obj, 8 obj: .zero 8 .ident "GCC: (GNU) 15.1.1 20250521 (Red Hat 15.1.1-2)" .section .note.GNU-stack,"",@progbits Here, as expected, the returned size is exactly what was passed into malloc. This is kinda OK because the input code is broken; there should be a NULL check before the allocated memory is evaluated with __builtin_dynamic_object_size. However we can do better here by wrapping the size into a simple check expression, i.e. (sz < offset_limit ? sz : 0).