I'm getting an assertion failure error when I attempt to delete a pointer at the end of my code. If I remove the delete statement there is no error.Any idea why? Thanks
I think it is because you are deleting buffer on line 34 but on line 35 you are setting it to be a null pointer. You dont have to do that. Just call
delete [] buffer;
Also you have a memory leak. You also need to delete "temp" like the following
delete [] temp;
so just swap out buffer = NULL; with delete [] temp; and hopefully it fixes it.
because you're deleting 'first', which is a buffer you didn't allocate with new.
You're misinterpretting the assignment operator. Here's what's happening:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// line 24
buffer = newchar[finalsize]; // GOOD - 'buffer' points to a newly allocated buffer
// line 26
char* temp = newchar[sizeM]; // GOOD - 'temp' points to a newly allocated buffer
// line 28
temp = first; // BAD - temp no longer points to your allocated buffer. Now it points to 'first'
// ie, if you try to delete[] temp now, it's the same thing as doing delete[] first, which
// is no good
// line 32
buffer = strcat(temp, last); // BAD
// strcat returns a pointer to the destination buffer (temp)
// so now 'buffer', 'temp', and 'first' all point to the same memory. You also lost your allocated buffers
// so they are impossible to delete at this point.
EDIT
Just to clarify... when dealing with C strings (char arrays), the = operator does NOT copy the string like you may expect. Instead, it changes what the pointer points to.
/EDIT
If you want to copy a C string, use strcpy:
1 2 3 4 5 6 7 8
// temp = first; // bad
strcpy(temp,first); // good
//-----
//buffer = strcat(temp,last); // bad
strcpy(buffer,temp);
strcat(buffer,last); // good
or... save yourself the headache and just use std::string. Problems like this disappear and you don't have to worry about memory leaks or buffer overflows:
1 2 3 4 5 6 7 8 9 10
//char first[MAX]; // get rid of these C strings
//char last[MAX];
string first; // replace with C++ strings
string last;
// now you can use assignment, and +=, and all that other good stuff
// and it'll work like you expect:
string fullname = first + " " + last;