为什么在谷歌测试中调用"mkdtemp()"时失败

Why does `mkdtemp()` fail when called in googletest?

本文关键字:quot 失败 mkdtemp 调用 为什么 谷歌 测试      更新时间:2023-10-16

我创建了一个小的RAII类,该类创建一个唯一的临时目录,并在销毁时再次将其删除。在Linux上,它使用mkdtemp()来实现这一点:

// temporaryDirectoryPath is an std::vector<char>
// containing u8"/tmp/nuclex-pixels-unittest-XXXXXX"
// Let mkdtemp() sort out a unique directory name for us (and create it!)
const char *directoryName = ::mkdtemp(&temporaryDirectoryPath[0]);
if(directoryName == nullptr) {
perror("mkdtemp() failed."); // DEBUGGING. REMOVE.
throw std::runtime_error("mkdtemp() failed.");
}

这在单独运行时运行得很好:ideone.com上的可运行代码


然而,如果我在GoogleTest 1.8.1单元测试中使用相同的代码,声明如下:

TEST(MyTestFixture, CanFlumbleTempDirectory) {
TemporaryDirectoryScope temporaryDirectory;
// Could call temporaryDirectory.GetPath() here...
}

失败:

Passing the following to mkdtemp(): /tmp/nuclex-pixels-unittest-XXXXXX
mkdtemp() failed.: Invalid argument

GoogleTest如何干扰mkdtemp()

传递给mkdtemp的字符串不可靠地以null结尾:

// Then append our directory name template to it
const char directoryNameTemplate[] = u8"nuclex-pixels-unittest-XXXXXX";
{
const char *iterator = directoryNameTemplate;
while(*iterator != 0) {
temporaryDirectoryPath.push_back(*iterator);
++iterator;
}
}

std::string不同,std::vector<char>不执行隐式空终止。如果"XXXXXX"后缀后面恰好有一个空字节,这是偶然发生的。情况是否如此取决于执行环境。