CodeQL 文档

返回局部 std::string 的 c_str

ID: cpp/return-c-str-of-std-string
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - reliability
   - correctness
Query suites:
   - cpp-security-and-quality.qls

单击查看 CodeQL 仓库中的查询

std::stringc_str 方法返回指向 std::string 所拥有内存缓冲区的原始指针。只有在 std::string 仍在作用域内时,该指针才安全使用。当 std::string 超出作用域时,会调用其析构函数,并释放内存,因此使用该指针不再安全。

示例

#include <string>

const char* hello() {
  std::string str("hello");
  return str.c_str();  // BAD: returning a dangling pointer.
}

建议

避免使用 C 字符串。在整个代码库中使用 std::string 更加安全,因为这样内存将自动管理。

如果必须使用 C 字符串,那么要非常小心地确保没有指向该字符串的指针能够超出该字符串的生命周期。例如,如果 C 字符串是在堆栈上分配的,那么将指向该字符串的指针存储在堆上的任何地方都是不安全的,除非您确定在函数结束之前会释放堆内存。

示例

#include <string>

std::string hello() {
  std::string str("hello");
  return str;  // GOOD: returning a std::string is safe.
}

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私