Cpp Char 数组越界的问题记录

看下面的代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
void uiChangeGraph(std::string_view path) {
  char tmp[FILENAME_BUF_SIZE]{ 0 };
  auto t = currentProject()->openGraph(path, tmp);
}

SightNodeGraph* Project::openGraph(std::string_view path, char* pathWithoutExtOut) {
  std::string targetPath{path};
  std::filesystem::path temp(targetPath);
  if (temp.has_extension()) {
    std::string ext = temp.extension().generic_string();
    if (ext == ".json" || ext == ".yaml") {
      targetPath = std::string(targetPath, 0, targetPath.rfind('.'));
    }
  }
  if (pathWithoutExtOut) {
    sprintf(pathWithoutExtOut, "%s", targetPath.c_str());
  }
  return currentGraph();
}

这段代码在函数uiChangeGraph结束的时候可能会出现内存错误, 原因是因为 tmp的内存不足,越界了。

增大 tmp 的大小, 或者做长度检测就可以解决问题了。

或者给openGraph函数添加一个长度参数, 然后使用 snprintf()函数。

0%