Re: [PATCH 01/12] include/xalloc: ensure arithmetics overflow cannot happen

Bernhard Voelker
2014-04-27T20:45:27Z

On 04/27/2014 10:05 PM, Sami Kerola wrote:
> The xrealloc() changes has the greatest change. It splits the size and
> multiplier arguments so that arithmetics overflow can be detected. This
> change is propagated to use of the function in other files.
>
> Additionally this change checks that size inputs for allocations are
> never zero. It is uncertain if in these cases abort() should be called
> to get a core.

I'd favor to see the behavior of the allocation functions to be harmonized
with gnulib: quite a couple of us guys may work in projects using it, thus
being familiar with its details and corner cases.
WDYT?

> The xstrdup() is made to use memcpy(), which is exactly what the library
> call does so one layer of absraction is saved here.
...
> static inline char __attribute__((warn_unused_result)) *xstrdup(const char *str)
> {
> - char *ret;
> -
> - if (!str)
> - return NULL;
> -
> - ret = strdup(str);
> + size_t len;
> + char *ret;
>
> - if (!ret)
> - err(XALLOC_EXIT_CODE, "cannot duplicate string");
> - return ret;
> + if (!str)
> + return NULL;
> + len = strlen(str) + 1;
> + ret = xmalloc(len);
> + memcpy(ret, str, len);
> + return ret;
> }

Hmm, while memcpy() alone is faster than strcpy(), replacing the
latter by strlen() + memcpy() certainly is not. The compilers and
libc are optimized enough, e.g. by using had-crafted assembler code,
that I think you don't have a chance to be faster by trying to be
smarter than them.

Have a nice day,
Berny