c++ - 为什么在googletest中调用 `mkdtemp()`失败?

标签 c++ cross-platform posix googletest

我创建了一个小型 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.");
}

单独运行时效果很好:runnable code on 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::vector<char>不执行隐式空终止,与 std::string 不同。如果"XXXXXX"后面碰巧有一个空字节,那么这会偶然发生。后缀。是否是这种情况取决于执行环境。

关于c++ - 为什么在googletest中调用 `mkdtemp()`失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58680718/

相关文章:

c - regexec() 无法匹配模式

c++ - 有符号/无符号比较

c++ - 当我需要修改键时,有什么方法可以避免 std::map 中的重新分配?

user-interface - Maveryx、FitNesse、Robot 在 Mac、Windows 和 Linux 上进行桌面 GUI 测试

c++ - 跨平台文件结构处理

c# - 在单声道中学习 C#

linux - POSIX 线程中的互斥概念

c - 如何检查文件描述符是否有任何可用数据?

android - 使用通过 CMAKE 构建的 Android NDK 时如何获取构建类型?

c++ - 枚举到数组绑定(bind)