Reputation: 23
I couldn't understand why there is an error at delete[] *iopszString;
,
can you help me fix it?
try the input: 1 3 aaa
If I omit the last delete[] it all works but it doesn't make sense because in order to exchange pointers I need to delete the previous point. The code
// 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;
// + "\0" 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;
}
Upvotes: 1
Views: 80
Reputation: 56863
The bug is in these two lines:
char* iopszString = new char[1];
iopszString = "";
You are allocating new memory with new
and you store its location in your pointer iopszString
. You then assign the location of the string literal ""
to that pointer, so the value of the pointer itself changes. It now points somewhere else, to a memory location that you haven't allocated with new
and that you don't own. You therefore lost the pointer of the memory you allocated (a memory leak) and when you call delete[]
on the pointer to the location of ""
, it crashes (as you can not free anything with delete[]
that you haven't allocated with new
.
You probably meant to write:
char* iopszString = new char[1];
iopszString[0] = '\0';
Which will only set the value of the first char
that you allocated to '\0'
and therefore turns it into a valid, empty, zero-terminated string.
Upvotes: 6