I have seen many pages for this error, but I'm not able to grasp what I'm doing wrong with my code, so I was hoping if I posted it, someone could shed some light.
This is a c++ class project. The goal is to write a function that takes two C strings (char*) and returns them concatenated together in a new. What I have here compiles, except for when I try to delete copycat, I get the malloc error in the title of this question.
How can I delete copycat?
I think I should be also deleting the "unused" news I created in the cat2 function (p, q), but that gives me the same error. What am I missing here with deallocating memory?
char* cat2(char* dest1, char* str2)
{
char* p = new char[100];
char* q = new char[100];
char* rvalue = new char[100];
for (p = dest1; *p != 0; p++)
{
;
}
for (q = str2; *q != 0; p++, q++ )
{
*p = *q;
}
*p = 0; /* set the last character to 0 */
rvalue = dest1;
return rvalue;
}
void main()
{
char s1[] = "Hello";
char s2[] = ", World!";
char* copycat = cat2(s1, s2);
cout << copycat;
delete copycat;
}
This is a c++ class project.Looks like mostlyCand very littleC++. - PaulMcKenziedeleteinstead ofdelete[]! Are you really being taught to write C++ in this manner? - Lightness Races in Orbitrvalue = dest1You therefore try to delete what comes froms2in main. If you made your parameters as follows:(const char* dest1, const char* str2)the bad code would not have compiled. - Neil Kirk