【问题标题】:Avoid memory leaks in C++ Pointers [closed]避免 C++ 指针中的内存泄漏 [关闭]
【发布时间】:2017-10-31 19:44:01
【问题描述】:
void append(char*& input,const char* str){
  size_t input_len = strlen(input);
  size_t str_len = strlen(str);

  size_t len = input_len + str_len;
  char* temp = new char[len + 1];

  memcpy(temp, input, input_len);
  memcpy(temp + input_len, str, str_len);
  // **#3** delete[] input;
  temp[len] = '\0';
  input = temp;
}
int main(){
  char* s = "string";

  cout << s << endl;
  append(s, " hello"); // **#1** not initialized by an array
  cout << s << endl;
  append(s, " welcome"); // **#2** now having an array
  cout << s << endl;
}

我想在分配新数组后删除以前分配的数组(#3)。但第一次 (#1) 将其称为具有动态分配的指针。

如何避免此类内存泄漏?
有没有办法用“新”识别内存分配?还是其他?

    if(p == new char[])...

看看这个,http://www.cplusplus.com/reference/cstring/strcat/它改变了原来的字符串

【问题讨论】:

  • 简短回答:您可以通过释放之前分配的内存来避免内存泄漏。
  • 简短的回答:不要使用指针!在您的情况下,使用字符串,您应该改用 std::string
  • 一般来说,std::unique_ptr 查一下。 en.cppreference.com/w/cpp/memory/unique_ptr
  • 如果您仍然坚持使用原始指针,而不是通过引用传递 input 并修改它指向的位置,而是 返回 新指针,并将 input 保留为.然后让调用者使用返回的指针释放内存。
  • std::string 的追加函数名为 +。

标签: c++ pointers memory-management memory-leaks


【解决方案1】:

我遵循一些简单的规则:

  • 不要手动分配内存。如果您发现自己正在编写手册 delete,请停下来三思而后行。
  • 使用 std::string 代替 C 风格的字符串
  • 使用std::vector&lt;T&gt; 代替C 数组(或std::array&lt;T&gt; 用于固定大小的数组)
  • 默认使用std::unique_ptrstd::make_unique
  • 如有必要,请使用std::shared_ptr
  • 对其他资源使用 RAII 包装器,例如文件

你的代码可以写得这么简单

// With C++17, we could use std::string_view for the input parameters
// I strongly prefer pure functions that don't mutate their arguments
std::string append(std::string const& s1, std::string const& s2) {
    return s1 + s2;
}

// the same function mutating the input argument. 
void append_mutate(std::string& s1, std::string const& s2) {
    s1 += s2;
}

int main(){
  std::string s = "string";

  cout << s << endl;
  s = append(s, " hello");
  cout << s << endl;
  append2(s, " welcome");
  cout << s << endl;
}

我也强烈建议不要使用 C 风格的字符串,尤其是 C 字符串。如果您有 C 背景或没有太多 C++ 经验,我会推荐 A Tour of C++

这些类的想法是RAII 的一个例子。基本原理是封装资源,例如内存或文件,放入拥有资源并在构造函数/析构函数中处理获取和释放的包装类。这提供了异常安全、确定性的资源处理。

【讨论】:

  • 你忘了:使用std::vector而不是字符串以外的动态数组的指针
  • @Someprogrammerdude 谢谢,已将其添加到列表中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-31
相关资源
最近更新 更多