避免C 指针中的内存泄漏

Avoid memory leaks in C++ Pointers

本文关键字:内存 泄漏 指针 避免      更新时间:2023-10-16
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] = '';
  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/它更改原始字符串

我遵循一些简单的规则:

  • 不要进行手动记忆分配。如果您发现自己编写手册delete,请停下来三思。
  • 使用std::string代替C风格字符串
  • 使用std::vector<T>代替C-Array(或固定尺寸数组的std::array<T>(
  • 默认使用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 没有太多经验,我建议您参观C 。

这些类的想法是RAII的一个例子。基本原则是封装资源,例如内存或文件,进入拥有资源的包装类,并在构造函数/驱动器中负责采集和发布。这提供了异常安全的确定性资源处理。