Compiling Lua (version 5.4.7) with the GCC 15.2.0 compiler as C++, I get a strange warning message
...\lauxlib.c|586|warning: 'memcpy' specified bound 18446744073709551614 exceeds maximum object size 9223372036854775807 [-Wstringop-overflow=]|
at the line
LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
char *b = prepbuffsize(B, l, -1);
memcpy(b, s, l * sizeof(char)); /* here*/
luaL_addsize(B, l);
}
}
What's wrong with this code?
This is a false positive warning from the compiler's static analysis.
The compiler is pointing out a theoretical problem that can't actually happen when the code runs.
The compiler is analyzing the memcpy
function call and sees a potential for overflow based on the data types involved.
The variable l
has the type size_t
. On a 64-bit system, size_t
is an unsigned 64-bit integer. Its maximum value is 2^64-1, which is 18,446,744,073,709,551,615
.
The C standard effectively limits the maximum size of any single object in memory to PTRDIFF_MAX
. On a 64-bit system, this is the maximum value of a signed 64-bit integer, which is 2^63−1, or 9,223,372,036,854,775,807
.
The compiler sees that l
(an unsigned type) could theoretically hold a value that is larger than the maximum possible object size. This is the value in your warning, 18446744073709551614
which is 2*PTRDIFF_MAX
. The compiler is warning you that if l
were this large, memcpy
would be instructed to copy more data than can possibly exist in a single memory object.
The compiler's analysis is too simplistic and misses a crucial piece of context from the line before the memcpy
.
char *b = prepbuffsize(B, l, -1);
memcpy(b, s, l * sizeof(char));
The prepbuffsize
function's job is to prepare a buffer of at least size l
.
An attempt to allocate a buffer of a size that large (e.g., more than 9,223,372,036,854,775,807
bytes) is guaranteed to fail on a real-world scenario.
When prepbuffsize
fails to allocate the memory, it will raise a Lua error.
This error stops the execution of the C function and propagates up to the Lua script.
Therefore, the memcpy
line is unreachable with a dangerously large value for l
. The program will have already aborted due to the allocation failure. The compiler isn't smart enough to deduce this inter-procedural logic and only sees the potential problem within the local scope of the luaL_addlstring
function.
You can safely ignore this warning. It is a known type of false positive when compiling large, mature codebases like Lua with aggressive warning flags.