Reputation: 13
I'm new to C++. I have written a program that allow user to add in file to my data folder. But now I want to also allow user to delete the files. So in the case below, it will displayed a list of available files from the data folder. The user chooses the file by entering the number, for example, [i] to delete the file from the list and also delete in the data folder. I have tried writing codes to delete it, but I got this error "Debug Assertion Failed". Is there something wrong with my delete?
case 'D':
case 'd':
myfiles = getFiles();
cout << "Current available objects:" << endl;
for (int i = 0; i < myfiles.size(); i++)
cout << '[' << i << ']' << ' ' << myfiles[i] << endl;
cout << endl << "Enter file number to delete or \"end\" to exit:";
while (cin >> str)
{
if (str == "end")
break;
input = str2int(str);
if (input >= 0 && input < myfiles.size())
{
//Delete object
newname = ExePath() + "/data/" + myfiles[input];
name = new char[newname.size() - 1];
strcpy(name, newname.c_str());
remove(name);
//Print out the available objects
cout << "\nCurrent available objects:" << endl;
for (int i = 0; i < myfiles.size(); i++)
cout << '[' << i << ']' << ' ' << myfiles[i-1] << endl;
cout << endl << "Enter file number to delete or \"end\" to exit:";
}
else cout << "Invalid input." << endl;
}
break;
Upvotes: 1
Views: 580
Reputation: 27518
I think it's this loop:
for (int i = 0; i < myfiles.size(); i++)
cout << '[' << i << ']' << ' ' << myfiles[i-1] << endl;
When i
is 0, then you are trying to access myfiles[-1]
. If myfiles
is not an object of a very strange class which overloads operator[]
in an unusual way, but is instead just a normal std::vector
(99% more likely :)), then this is undefined behaviour, i.e. anything can happen (including the error message you see).
As a side note, you are performing pointer operations instead of using real C++ strings (i.e. std::string
objects) consistently. Which is surprising, because you already seem to have a std::string
there (newname
), and you seem to know how to use it together with (old / legacy / C) functions requiring a char const *
, namely with its c_str()
member function. Why don't you just write remove(newname.c_str())
?
Upvotes: 2
Reputation: 9743
At least you should use
name = new char[newname.size() + 1];
instead of
name = new char[newname.size() - 1];
Anyway, I don't see the need to copy the string. What will also fail is:
myfiles[i-1]
in your second loop, because it starts from 0.
Upvotes: 1