After debugging for half a day, I found the crash caused by the delete operation. I suspect that after applying for memory for a long time, the pointer operation went wrong, causing something to be written to the memory area that was not applied, an error occurred while releasing.
However, this delete operation sometimes has problems and sometimes does not.
Later, I posted a post on the School Forum and got a reminder. It may be because of a problem with the statement for applying for memory and releasing memory, which I did not expect before.
Yes:
My original code is:
char *msg2 = new char(2+(sp->first).size()+sizeof(in_addr_t)+sizeof(in_port_t));
Release code:
Delete msg2; // The program crashes during the delete operation. Why?
Because I used the msg2 pointer to operate on memory that is not applied for by me.
The correct code should be
char *msg2 = new char[2+(sp->first).size()+sizeof(in_addr_t)+sizeof(in_port_t)];
The correct release code should be:
delete []msg2;
Note the difference between () and [] After new.
The Applied memory should be
Char * p = new char [10]; // assume that the request is for 10 bytes.
Char * p = new char (10); // apply for a byte memory and assign the value of this byte memory to 10
The difference is too big.
The release should be
Combination of new and delete
Combination of new [] and delete []