Re: delete[] causing DAMAGE
raan wrote:
Whats wrong with the code ? delete[] tp; is throwing DAMAGE: After
normal block(#56) at 0x00321480
Environment, VS2003, XP
#include <iostream>
#include <fstream>
#include <string>
#include <set>
#include <stack>
#include <sstream>
using namespace std;
string PutS(std::string& type)
{
char *tp;
tp = new char[type.length()+1];
What's the intent? If you need to append 's' to your string,
shouldn't you then allocate +2 and not +1?
type.resize(type.length() + 1);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Why do you do that? Do you realise that 'length()' will
now return a different value?
memcpy(tp, type.c_str(), strlen(type.c_str()));
*(tp + type.length()-1) = 's';
*(tp + type.length()) = '\0';
You allocated fewer characters than you're trying to access.
string ntype(tp);
cout << ntype.c_str();
delete[] tp;
return ntype;
}
int main()
{
std::string type = "CAMERA";
PutS(type);
getchar();
}
I am not sure why you're doing all this dancing around with
naked pointers. Why don't you simply define a local string,
initialise it from the string passed in, and then append
something to it using += ?
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask