5

The program contains code like follows:

int size;
...
int *pi = (int*)calloc(size, sizeof(int));
...

Here is the error message when compiled with gcc7.2:

error: argument 1 range [18446744071562067968, 18446744073709551615] exceeds maximum object size 9223372036854775807 [-Werror=alloc-size-larger-than=]

When I change
int *pi = (int*)calloc(size, sizeof(int)); to
int *pi = (int*)calloc((unsigned int)size, sizeof(int));

The error disappeared.

However, in the program, there are many malloc and calloc used like my original version.

Why there is only one error detected by gcc?

Yuan Wen
  • 1,583
  • 3
  • 20
  • 38

3 Answers3

6

I recently had the same problem on my GCC 9.1 build, and I found this discussion on the GCC Bugzilla:

https://gcc.gnu.org/bugzilla//show_bug.cgi?id=85783

As mentioned in the link discussion, I was able to suppress the warning by checking the size parameter against PTRDIFF_MAX.

Kurt
  • 61
  • 1
  • 4
  • 1
    What's wrong with this answer? It answers the question by showing the link to the bug report and provides a workaround. I do not think it merits deletion. – L. F. Jun 22 '19 at 01:14
3

The warning mentions a maximum object size of 9223372036854775807 (0x7FFFFFFFFFFFFFFF). It is an implementation defined value. size_t must be large enough to hold that value, and indeed, being unsigned, it can take the double of that number. The calloc() function multiplies two size_t values, its arguments nmemb and size. The resulting value can obviously exceed the maximum object size.

Well written programs are coded so as to never allow exceeding values in the arguments. However, if gcc is not able to locate such check, it issues a warning. Casting to a 4 byte integer would truncate exceeding values and make compiler happy.

Ale
  • 887
  • 10
  • 14
1

The warning depends on the range that GCC thinks size has. At that particular point in the program it is deemed to be in that (exceedingly large) range. At the other malloc/calloc callsites perhaps it wasn't so large.

It would largely depend on how size is calculated at different points in the program. Of course, making sure that it is actually initialised before any use is the first step.

Kyrill
  • 2,963
  • 1
  • 8
  • 12