为什么我的删除功能总是出现分段错误

Why do I keep getting a segmentation fault with my delete function

本文关键字:分段 错误 我的 删除 功能 为什么      更新时间:2023-10-16

>我有一个任务,我需要使用重载析构函数来删除动态分配的指针。但是,当它运行时,我的一些指针被删除,直到我的一个对象的指针出现分段错误,一个指向"和第二个"的指针是使用参数化构造函数制作的。 我试图通过并确保删除运算符有括号(因为我的新运算符这样做了),我通过打印出它的信息和地址来确保对象仍然存在。我试图重写我的分配函数,并试图检查我的析构函数以查看它在哪里搞砸了。 如果有帮助,我已经包括了我的析构函数、我的分配函数、我的释放函数和我的参数化构造函数。

'''
//Destructor
MyString::~MyString()
{
buffer_deallocate();
};
void MyString::buffer_deallocate() {
cout << m_buffer << endl;
delete[](m_buffer);
m_buffer = NULL;
m_size = 0;
}
void MyString::buffer_allocate(size_t size) {
try {
m_buffer = new char[size];
m_size = size;
}
catch(bad_alloc&)
{
cout << "Errror: Unable to allocate memory" << endl;
buffer_deallocate();
}
}

//Parameterized Constructor
MyString::MyString(const char * str)
:m_size(0)
{
const char * strPtr = str;
while(*strPtr)
{
strPtr++;
m_size++;
}
buffer_allocate(m_size);
for(int i = 0; i < m_size; i++)
{
m_buffer[i] = str[i];
}
};
'''

但是每次我都会得到"和第二个"之后的输出 分段故障(核心转储)

编辑:我已经尝试了大部分推荐的内容。至少据我所知,问题仍然存在,我现在意识到我的代码有点稀疏。(请原谅我,我还在学习。以下是新代码以及函数文件的其余部分以供参考:

'''
#include<iostream>
#include<string.h>
using namespace std;
#include"MyString.h"

//Default Constructor
MyString::MyString()
:m_size(0), m_buffer(NULL)
{
buffer_allocate(0);
};

//Parameterized Constructor
MyString::MyString(const char * str)
:m_size(strlen(str)+1), m_buffer(NULL)
{
buffer_allocate(m_size);
strncpy(m_buffer, str, m_size);
};

//Copy Constructor
MyString::MyString(const MyString & other)
:m_size(0), m_buffer(NULL)
{
const char * otherPtr = other.c_str();
buffer_allocate(other.size());
for(int i = 0; i < size(); i++)
{
m_buffer[i] = otherPtr[i];
}
m_buffer[m_size] = '';
};

//Destructor
MyString::~MyString()
{
buffer_deallocate();
};

size_t MyString::size() const
{
return m_size;
}

size_t MyString::length() const{
return m_size-1;
}

const char * MyString::c_str() const{
return m_buffer;
}

bool MyString::operator==(const MyString & other) const {
char * m_bufferPointer = m_buffer;
while(*m_bufferPointer++)
{
const char * str_ptr = other.c_str();
if(*m_buffer != *str_ptr++)
{
return 0;
}
}
return 1;
}

MyString & MyString::operator=(const MyString & rhs) {
buffer_deallocate();
buffer_allocate(rhs.size());
const char * c_strPtr = rhs.c_str();
int i;
for(i = 0; i < rhs.size(); i++)
{
this->m_buffer[i] = c_strPtr[i];
}
return *this;
}


MyString MyString::operator+ (const MyString & other_myStr) const {
char * temp_pointer;
temp_pointer;
size_t temp_size = m_size + other_myStr.size();
//New Combined Buffer for Concatanation
try {
temp_pointer = new char[temp_size];
temp_pointer = strcat(this->m_buffer, other_myStr.c_str());
}
catch(bad_alloc&)
{
cout << "Error: Unable to Allocate Memory";
return NULL;
}
return MyString(temp_pointer);
}

char & MyString:: operator[](size_t index) {
return m_buffer[index];
}

const char & MyString::operator[] (size_t index) const {
return m_buffer[index];
}

ostream & operator << (ostream& os, const MyString & myStr) {
os << myStr.m_buffer;
return os;
}
void MyString::buffer_deallocate() {

cout << "Trying to delete : " <<m_buffer << endl;
if(m_buffer){
delete[](m_buffer);
}
cout << " Success" <<endl;
m_buffer = NULL;
m_size = 0;
}
void MyString::buffer_allocate(size_t size) {
try {
m_buffer = new char[size];
m_size = size;
}
catch(bad_alloc&)
{
cout << "Errror: Unable to allocate memory" << endl;
m_size = 0;
}
}

'''

inMyString::buffer_deallocate

cout << m_buffer << endl;

要求m_buffer以 null 结尾。不幸的是,MyString::MyString(const char * str)不作此保证。

你可以

for(int i = 0; i < m_size; i++)
{
cout << m_buffer[i] << endl;
}

逐个字符打印出字符串,但浪费一个字节、null 终止并利用标准库可能更有用

MyString::MyString(const char * str)
:m_size(0)
{
const char * strPtr = str;
while(*strPtr)
{
strPtr++;
m_size++;
}
buffer_allocate(m_size); 
for(int i = 0; i < m_size; i++)
{
m_buffer[i] = str[i];
}
m_buffer[m_size] = ''; // add the null
}

然后

void MyString::buffer_allocate(size_t size) {
try {
m_buffer = new char[size+1]; // +1 for the null terminator
m_size = size;
}
catch(bad_alloc&) // this is a bad thing to do here. More on that later.
{
cout << "Errror: Unable to allocate memory" << endl;
buffer_deallocate();
}
}

但是我们可以通过一些库函数调用来简化这一点。

MyString::MyString(const char * str)
:m_size(strlen(str))
{
buffer_allocate(m_size);
strcpy(m_buffer, str);
}

补遗:

您的班级可能违反了三法则。如果MyString没有复制构造函数和赋值运算符来配合析构函数,则任何副本,无论是有意还是无意的,都会将MyString变成定时炸弹。其中一个副本的析构函数将先于其他副本运行,而其他副本没有有效的m_buffer

MyString::buffer_allocate无法安全地返回void,除非它允许异常传播。捕获bad_alloc会使对象在m_buffer没有有效的分配,程序的其余部分将不知道这一点。程序中的所有其他访问都必须测试有效的缓冲区,或者尝试访问无效内存的未定义行为。最好让异常失败,并被程序的另一部分捕获,该部分更适合决定要做什么。

如果在m_buffer处已经具有有效分配的MyString上调用,MyString::buffer_allocate将泄漏现有分配。我推荐一个

if (m_buffer) 
{
delete[] m_buffer;
}

并在MyString的构造函数中将m_buffer初始化为 null

MyString(const char* str)
: m_size(std::strlen(str)), m_buffer(nullptr) 
{
buffer_allocate(m_size);
std::strncpy(m_buffer, str, m_size);
}

所以我不得不将其重新制作为一些工作代码。 问题可能是字符串长度必须扩展为 1 才能添加 nul 终止。因此,可以:

// prevent some MSVS warnings->errors
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <cstring>

//Destructor
class MyString {
private:
size_t m_size;
char* m_buffer;
void buffer_allocate(size_t size) {
try {
m_buffer = new char[size];
m_size = size;
}
catch (std::bad_alloc&)
{
std::cout << "Errror: Unable to allocate memoryn";
// allocation failed, nothing changed, don't delete/
m_size = 0;
}
}
void buffer_deallocate() {
// printing in the buffer deallocation??
delete[] m_buffer;
m_buffer = nullptr;
m_size = 0;
}
public:
MyString(const char* str)
: m_size(std::strlen(str)+1) // add null termination
, m_buffer(nullptr)
{
buffer_allocate(m_size);
std::strncpy(m_buffer, str, m_size);
}
~MyString() {
buffer_deallocate();
}
void Print() const {
std::cout << m_buffer << 'n';
}
};
int main() {
std::string input{ "Hello World!" };
MyString myString(input.c_str());
myString.Print();
}