在将字符串大小(string :: npos)分配给整数变量时,在隐式常量转换警告中溢出

时间:2016-08-17 10:48:42

标签: c++ gcc warnings integer-overflow

如何摆脱下面的警告?

size_t filesize = getFilesize(strLogFileName.c_str());
// Open file
int fd = open(strLogFileName.c_str(), O_RDONLY, 0);
assert(fd != -1);
// Execute mmap
char* mmappedData =
    (char *) mmap(NULL, filesize, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);
assert(mmappedData != NULL);
string strFileContent(mmappedData);

// warning: overflow in implicit constant conversion
int pos, lpos = string::npos;

修复此警告的代码可能需要进行哪些更改,而不是忽略此警告?

2 个答案:

答案 0 :(得分:4)

使用正确类型:

size_t pos, lpos = std::string::npos;

auto。我们不会使用int s或任何signed索引标准容器。请注意pos未初始化。

答案 1 :(得分:4)

string::npos的类型为size_t。将size_t分配给int可能会导致转换期间出现溢出。修复如下:

size_t pos;
size_t lpos = string::npos;

或者,根据user2079303的建议,如果您想支持使用自定义分配器的字符串,则可以使用string::size_type或更方便地使用auto