上次删除时出错[]
Error at the last delete[]
我不明白为什么delete[] *iopszString;
有错误,你能帮我解决它吗?
尝试输入:1 3 aaa
如果我省略最后一个删除[],它都可以工作,但它没有意义,因为为了交换指针,我需要删除前一点。代码
// Notepad.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Method definition
void addText(char** iopszString);
void main()
{
// Const definition
int const ADD = 1;
int const UPDATE = 2;
int const DELETE = 3;
int const SAVE = 4;
int const EXIT = 5;
// Variable definition
int nUserCode;
// Code section
// Gets the user code
cout << "Enter the code: " << endl;
cin >> nUserCode;
// + " " so 1 minimum!!!
char* iopszString = new char[1];
iopszString = "";
// Runs until the exit code
while (nUserCode != EXIT)
{
// Checks the exit code
switch (nUserCode)
{
case ADD:
{
addText(&iopszString);
cout << iopszString << endl;
break;
}
case UPDATE:
{
break;
}
case DELETE:
{
break;
}
case SAVE:
{
break;
}
default:
{
cout << "Wrong code, try again" << endl;
break;
}
}
// Gets the user code
cout << "Enter the code: " << endl;
cin >> nUserCode;
}
// Delete the string cuz heap
delete[] iopszString;
}
void addText(char** iopszString)
{
// Variables definition
int nAddLength;
// Code section
// Gets the new length
cout << "Enter the length of the added string: " << endl;
cin >> nAddLength;
// Always remember - the length you want+1!!
char* szNewString = new char[nAddLength+1];
// Gets the new string
cout << "Enter the new string which you want to add: " << endl;
cin >> szNewString;
// Creating a new string (result)
char* szResult = new char[nAddLength+1+strlen(*iopszString)];
// Copies the old string to the new
strcpy(szResult, *iopszString);
strcat(szResult, szNewString);
// Deletes the new string cuz we already copied
delete[] szNewString;
// Exchange pointers
//strcpy(*iopszString, szResult); <--- never
// The problem!
delete[] *iopszString;
// Exchange pointer
*iopszString = szResult;
}
错误在这两行中:
char* iopszString = new char[1];
iopszString = "";
您正在使用new
分配新内存,并将其位置存储在指针iopszString
中。然后,将字符串文本""
的位置分配给该指针,以便指针本身的值更改。它现在指向其他地方,指向您尚未分配new
且您不拥有的内存位置。因此,您丢失了分配的内存的指针(内存泄漏),当您在指向""
位置的指针上调用delete[]
时,它会崩溃(因为您无法释放任何未分配delete[]
new
。
你可能想写:
char* iopszString = new char[1];
iopszString[0] = ' ';
这将仅设置分配给' '
的第一个char
的值,因此将其转换为有效的空字符串。
相关文章:
- 如何删除已输入的书以及如何使标题,语言和名称在上面放置空格不会出错?
- 尝试删除链表的头部或中间节点时出错
- 从BST删除节点时出错
- static_cast为int时删除布尔运算符时出错
- 删除时出错:表达式必须是指向完整对象类型的指针
- 删除动态分配的数组时出错
- 删除函数中的对象:丑陋、容易出错、效率低下,而且通常不安全
- 删除treap时出错
- 删除动态数组c++时出错
- 在运行时从指针到指针数组中删除字符串时出错
- 分段 删除链表的项目时出错
- 删除指针时出错
- 上次删除时出错[]
- 通过函数后从列表中删除项目时出错
- 尝试引用已删除的函数时出错
- 尝试将上一个节点链接到要删除的节点之后的节点时出错
- 编译器尝试删除作为指针的模板类型时出错
- 删除C++中的文件时出错
- 析构函数删除数组时出错
- 删除矢量中的指针时出错