我使用 GCC 10.2.0 和 C++17,出现以下错误:
ioapi.c: In function ‘file_build_ioposix’:
ioapi.c:125:5: warning: ‘strncpy’ specified bound depends on the length of the source argument [-Wstringop-overflow=]
125 | strncpy(ioposix->filename, filename, ioposix->filenameLength);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ioapi.c:123:31: note: length computed here
123 | ioposix->filenameLength = strlen(filename) + 1;
这是我的代码:
static voidpf file_build_ioposix(FILE *file, const char *filename)
{
FILE_IOPOSIX *ioposix = NULL;
if (file == NULL)
return NULL;
ioposix = (FILE_IOPOSIX*)malloc(sizeof(FILE_IOPOSIX));
ioposix->file = file;
ioposix->filenameLength = strlen(filename) + 1;
ioposix->filename = (char*)malloc(ioposix->filenameLength * sizeof(char));
strncpy(ioposix->filename, filename, ioposix->filenameLength);
return (voidpf)ioposix;
}
这里的问题是这应该被认为是好的,因为目的地设置为源长度+ 1,但它仍然提供错误。
尝试检查失败的 malloc,但没有改变任何东西。
src
复制字符,直到遇到 '\0'
或复制 count
符号,以先到者为准。该警告反映了分配 count
字节并将相同的 count
传递给 strncpy()
通常是危险的:您最终可能会得到一个非空终止的字符串。在这种特定情况下你不会,因为 src[count-1]
保证是 '\0'
但似乎警告系统错过了这一点。
请注意,“警告”不是“错误”,对于完全正确的代码,可能会发出警告。