Sujet : Re: VMS
De : invalid (at) *nospam* invalid.invalid (Richard Kettlewell)
Groupes : comp.os.linux.miscDate : 22. Jun 2025, 15:27:22
Autres entêtes
Organisation : terraraq NNTP server
Message-ID : <wwvplev3l85.fsf@LkoBDZeT.terraraq.uk>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
User-Agent : Gnus/5.13 (Gnus v5.13) Emacs/28.2 (gnu/linux)
candycanearter07 <
candycanearter07@candycanearter07.nomail.afraid>
writes:
Robert Riches <spamtrap42@jacob21819.net> wrote at 03:43 this Saturday (GMT):
Some years ago, I heard of a bug related to use of malloc. The code
had _intended_ to dynamically allocate storage for a string and the
terminating null byte. It was _intended_ to do this:
>
dest = malloc(strlen(src)+1);
>
Instead, a paren was misplaced:
>
dest = malloc(strlen(src))+1;
>
IIUC, the next line copied the src string into the newly-
allocated destination.
>
Aren't you supposed to multiply by sizeof as well?
No, because strlen already gives you the number of bytes, excluding the
0 terminator.
It’s also worth noting that in general malloc(n * sizeof something) is a
vulnerability if there’s any possibility of adversarial control over the
length ‘n’; the multiply operation can overflow size_t and lead to
allocating a lot less space that required. This isn’t particularly
relevant to strings on most platforms (because multiplying by 1 can’t
overflow) but if you are multiplying anything by a size and passing thr
product to malloc or realloc, you may have a problem.
In principle the fix is to use calloc(), and your C runtime will return
an error if an overflow would occur. That said, in practice C runtimes
were still being found to get this wrong as recently as 2021 so
depending on how mainstream your target platform is, you might want to
check...
Those who had worked on that project longer said the bug had been
latent in the code for several years, most likely with alignment
padding masking the bug from being discovered. Curiously, the
bug made itself manifest immediately upon changing from a 32-bit
build environment to a 64-bit build environment.
>
I'm more surprised it didn't segfault. Any idea what caused it to not?
I know strlen doesn't account for the terminating character, but it
seems like it should've been TWO bytes shorter...
Segmentation faults don’t happen for all out of bounds accesses, they
happen if you access a page which isn’t mapped at all or if you don’t
have permission on that page for the operation you’re attempting. The
example discussed here would only trigger a segmentation fault if the
allocation finished at the end of a page, otherwise you’ll just read or
write padding bytes, or the header of the next allocation.
-- https://www.greenend.org.uk/rjk/