Menu

#21 Implement reallocarray to harden memory allocation in giflib

Unstable_(example)
closed
1
2015-05-28
2015-03-10
No

OpenBSD has developed reallocarray() which is an API that makes integer overflow detection easier when allocating memory.

This has helped to fix one issue in Henry Spencer's regex library that affected FreeBSD and NetBSD, but not OpenBSD.

Quoting from OpenBSD's man page:
size_t num, size;
...

/ Check for size_t overflow /
if (size && num > SIZE_MAX / size)
errc(1, EOVERFLOW, "overflow");

if ((p = malloc(size * num)) == NULL)
err(1, "malloc");

The above test is not sufficient in all cases. For example, multiplying ints requires a different set of checks:

int num, size;
...

/ Avoid invalid requests /
if (size < 0 || num < 0)
errc(1, EOVERFLOW, "overflow");

/ Check for signed int overflow /
if (size && num > INT_MAX / size)
errc(1, EOVERFLOW, "overflow");

if ((p = malloc(size * num)) == NULL)
err(1, "malloc");

Assuming the implementation checks for integer overflow as OpenBSD does, it is much easier to use calloc() or reallocarray().
The above examples could be simplified to:

if ((p = reallocarray(NULL, num, size)) == NULL)
err(1, "reallocarray");

I have attempted to write an initial patch for giflib.

Comments welcomed.

1 Attachments

Related

Patches: #21

Discussion

  • loganaden Velvindron

    Dear All,

    I have updated the patch, for realloc() to reallocarray().

     
  • Eric S. Raymond

    Eric S. Raymond - 2015-05-28
    • status: open --> closed
    • assigned_to: Eric S. Raymond
     
    • loganaden Velvindron

      On Thu, May 28, 2015 at 9:07 AM, Eric S. Raymond esr@users.sf.net wrote:

      status: open --> closed
      assigned_to: Eric S. Raymond


      [patches:#21] Implement reallocarray to harden memory allocation in giflib

      Hi,

      Eric,

      Thank you for reviewing and accepting the patch.

      I attached an updated patch in the comment.

      Please see: http://sourceforge.net/p/giflib/patches/21/#a9fb

       

      Related

      Patches: #21


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.