c++ - 尝试删除字符数组时崩溃

标签 c++ arrays char new-operator delete-operator

当它到达 test2 需要删除 String 对象的删除部分时,它崩溃了。我不确定它为什么会崩溃。它说“调试断言失败!”。我是否删除了动态分配的字符数组错误?

strdrv.cpp:

#include <iostream>
#include <stdlib.h>
#include "strdrv.h"

int main() {
test2();
return 0;
}
void test2() {
cout << "2. Testing S2: String one arg (char *) constructor."
    << endl << endl;
csis << "2. Testing S2: String one arg (char *) constructor."
    << endl << endl;
String s2("ABC");
s2.print();
wait();
}

字符串.cpp:

#include "String.h"
#include <iostream>

using namespace std;
String::String(char* s) {
int sLength = 0;

for (int i = 0; s[i] != '\0'; i++) {
    sLength++;
}

buf = new char[sLength+1];
dynamicallyAlloc = true;
buf = s;

length = sLength;

/*buf[length] = '\0';*/ 
}

String::~String() {
if(dynamicallyAlloc)
    delete []buf;
}

字符串.h:

#ifndef _STRING_H
#define _STRING_H

#include <iostream>

using namespace std;

class String {
protected:
bool dynamicallyAlloc;
char nullChar;
int length;
char* buf;
void calculateStringLength();


public:
String();
String(char*);
String(char);
String(int);
String(const String&);
String(char, int);
~String();
int getLength() const;
char* getString() const;
String& operator=(const String&);
String& operator=(const char*);
String& operator+=(const String&);
String operator+() const;
char& operator[](int);
String& operator++();
String& operator--();
String operator++(int);
String operator--(int);
String substr(int, int);
void print();
friend String operator+(const String&, const String&);
friend String operator+(const String&, const char*);
friend String operator+(const char*, const String&);
friend String operator+(const String&, char);
friend String operator+(char, const String&);
friend char* operator+(const String&, int);
friend char* operator+(int, const String&);
friend int operator==(const String&, const String&);
friend int operator!=(const String&, const String&);
friend int operator<(const String&, const String&);
friend int operator<=(const String&, const String&);
friend int operator>(const String&, const String&);
friend int operator>=(const String&, const String&);
friend ostream& operator<<(ostream& os, const String& s1);
};

#endif

最佳答案

复制数组内容,不复制指针,而是

buf = s;

你要复制内容

memcpy(buf,s, sLength+1);

这会保留您分配的 buf 供以后删除。

关于c++ - 尝试删除字符数组时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17847703/

相关文章:

C++通过类模板函数中的指针访问类方法

C 中的 Char 数组串联格式

c - 如果同一输入位置可能有 char 或 int,如何 scanf

android - 需要关于使用 const 参数覆盖函数的警告

c++ - Qt/C++ - 从派生类调用覆盖方法

java - n 个数字排成一个圆圈。我们需要找到连续 nos 的最大总和

c - sscanf 获取剩余字符串的值

java - 为什么 String[] 比 char[] 占用更多空间?

c++ - Qt 槽和信号 : Input QPushButton as a parameter?

arrays - 在 Puppet 中循环数组