Bug 96916 - warning: ‘strndup’ specified bound 18446744073709551615 exceeds maximum object size 9223372036854775807 [-Wstringop-overflow=]
Summary: warning: ‘strndup’ specified bound 18446744073709551615 exceeds maximum objec...
Status: RESOLVED INVALID
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: 10.2.1
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: diagnostic
Depends on:
Blocks:
 
Reported: 2020-09-03 09:58 UTC by Richard W.M. Jones
Modified: 2020-09-03 13:39 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Richard W.M. Jones 2020-09-03 09:58:56 UTC
I'm not certain this is really a bug, but I don't understand it.  A simple reproducer:

----------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

const char *
copyn (const char *str, size_t n)
{
  return strndup (str, n);
}

const char *
copy (const char *str)
{
  return copyn (str, SIZE_MAX);
}
----------------------------------------------------------------------

$ gcc -O2 -Wall -c test.c
In function ‘copyn’,
    inlined from ‘copy’ at test.c:15:10:
test.c:9:10: warning: ‘strndup’ specified bound 18446744073709551615 exceeds maximum object size 9223372036854775807 [-Wstringop-overflow=]
    9 |   return strndup (str, n);
      |          ^~~~~~~~~~~~~~~~

$ gcc --version
gcc (GCC) 10.2.1 20200826 (Red Hat 10.2.1-3)
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


Note that it seems as if the compiler is claiming that strndup cannot cope with a string larger than ssize_t (rather than size_t), which is unexpected.
Comment 1 Richard Biener 2020-09-03 10:56:57 UTC
There's an implementation-defined limit of object sizes induced by the
representation of the difference of addresses into such object which
is then exactly half the address space.
Comment 2 Martin Sebor 2020-09-03 13:31:04 UTC
Yes, the warning is by design and is issued for any built-in function that takes an argument specifying the size of an object (malloc, memcpy, etc.).  It's meant to help identify calls to allocation functions that are certain to fail or that will overflow the destination.  Passing in PTRDIFF_MAX instead should avoid the warning (as would of course calling strdup).
Comment 3 Martin Sebor 2020-09-03 13:39:18 UTC
For strndup POSIX mentions the following application usage:

Implementations are free to malloc() a buffer containing either (size + 1) bytes or (strnlen(s, size) + 1) bytes. Applications should not assume that strndup() will allocate ( size + 1) bytes when strlen(s) is smaller than size.