尝试删除字符数组时崩溃
Crashing when trying to delete character array
当它到达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();
}
String.cpp:
#include "String.h"
#include <iostream>
using namespace std;
String::String(char* s) {
int sLength = 0;
for (int i = 0; s[i] != ' '; i++) {
sLength++;
}
buf = new char[sLength+1];
dynamicallyAlloc = true;
buf = s;
length = sLength;
/*buf[length] = ' ';*/
}
String::~String() {
if(dynamicallyAlloc)
delete []buf;
}
String.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
,以便以后删除。
相关文章:
- 类对象数组的问题会导致崩溃
- 字节数组初始化会导致 DirectX 崩溃
- 使用 sf::Text 数组时崩溃
- For 循环在尝试读取数组 c++ 时程序崩溃
- 删除数组 c++ 崩溃问题
- 如果类的成员,C++数组会导致崩溃
- 在C++中删除指针数组时析构函数崩溃
- 在 C++ 中使用平展数组语法,崩溃取决于宽度/高度
- 我的单例中的数组在离开函数后没有保留信息,然后在尝试再次访问信息时崩溃
- C++ rezing 动态数组最多可以处理一定数量的元素,但在某些时候会崩溃并显示错误 (0XC0000005)
- 释放字符的动态数组时崩溃
- size_t结构非数组成员崩溃的强制转换
- C++程序在迭代到数组的最后一个元素时崩溃
- 从数组比较2个字符串时,程序崩溃
- C++ 尝试向类内的数组(或向量)添加值时程序崩溃
- 内存相关崩溃:Cocos2d游戏中的三维数组
- 尝试获取数组中的最小元素时崩溃
- 动态数组在构造函数处崩溃
- 使用数组的单向链表:它在运行时崩溃
- C 程序崩溃(数组和2个指针Binsearch功能)