我目前正在做一项作业,我正在努力调试我的内存泄漏。我的程序运行并通过了,但是,当我上传它进行评分时,我的代码发生了内存泄漏。如果有人能指出我正确的修复方法,我将不胜感激!
我已经尝试了所有我能想到的!
#ifndef A2_HPP
#define A2_HPP
#include <algorithm>
class sorted_sc_array {
public:
/*
* return: none
* constructor with no argument assign size_ = 0 and ptr_ to null pointer
*/
sorted_sc_array() : size_(0), ptr_(nullptr) {
}
/*
* return: none
* destructor delete the pointer ptr_
*/
~sorted_sc_array() {
delete[] ptr_;
}
/*
* return: none
* when assign an object to new object
*/
sorted_sc_array(const sorted_sc_array& A){
const signed char* str = A.data();
int sz = A.size_;
this->size_ = 0;
for(int i = 0; i < sz; i++) this->insert(str[i]);
delete[] str;
}
/*
* return: sorted_sc_array
* overloading of operator =
*/
sorted_sc_array& operator=(const sorted_sc_array& A){
const signed char* str = A.data();
int sz = A.size_;
this->size_ = 0;
for(int i = 0; i < sz; i++) this->insert(str[i]);
}
/*
* return int
* return the size of the ptr_
*/
int size() const {
return size_;
}
/*
* return char*
* return the deta stored in the pointer ptr_
*/
const signed char* data() const {
return ptr_;
}
/*
* return void
* add new char to the pointer ptr_ and sort the the new string after the addition
*/
void insert(signed char c) {
signed char *str = (signed char*)malloc((size_ + 1)*sizeof(char));
for(int i = 0; i < size_; i++) str[i] = ptr_[i];
str[size_++] = c;
ptr_ = (signed char*)malloc((size_)*sizeof(char));
for(int i = 0; i < size_; i++) ptr_[i] = str[i];
std::sort(ptr_, ptr_ + size_);
delete[] str;
}
private:
int size_; // size of the array
signed char* ptr_; // pointer to the array
}; // class sorted_sc_array
#endif // A2_HPP
这是测试类:
/*
* File: a2.pp
* Description: testing class a2.hpp
*/
#include <iostream>
#include "a2.hpp"
int main(int argc, char* argv[]) {
sorted_sc_array A;
{
sorted_sc_array T;
for (signed char c = -128; c < 127; ++c) T.insert(c);
T = T;
sorted_sc_array V = T;
A = V;
}
const auto first = A.data();
const auto last = first + A.size();
auto size = A.size();
bool res = std::is_sorted(first, last);
if (!res || (A.size() != 255)) std::cout << "fail";
else std::cout << "pass";
std::cout << std::endl;
return 0;
} // main
代码编译并执行,“通过”但是某处存在内存泄漏! :(
最佳答案
显示的代码中存在多个错误。
在复制构造函数中:
delete[] str;
这会删除另一个对象的缓冲区。另一个对象的析构函数将尝试 delete[]
当它被销毁时,它自己的缓冲区再次出现。这将导致内存损坏和未定义的行为。
明显的内存泄漏在你的 insert()
中:
ptr_ = (signed char*)malloc((size_)*sizeof(char));
这里同时存在两个错误。
使用
malloc
对于析构函数最终将delete[]
的缓冲区.只有new
-ed 对象可以是delete[]
d.使用delete
对于malloc
-ed 内容是未定义的行为。ptr_
的先前内容没有明确delete
d,从而泄漏内存。
insert()
,总的来说,就是在做不必要的分配。那里不需要两次分配缓冲区。只有一次分配就足够了:分配,将内容复制到新缓冲区,delete
老ptr_
, 并设置 ptr_
到新分配的缓冲区。
关于C++ 调试帮助内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39939248/