避免C 指针中的内存泄漏
Avoid memory leaks in C++ Pointers
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_ptr
和std::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的一个例子。基本原则是封装资源,例如内存或文件,进入拥有资源的包装类,并在构造函数/驱动器中负责采集和发布。这提供了异常安全的确定性资源处理。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏