Insects - misuse about new []delete []

xiaoxiao2021-03-06  52

Today, I read "C traps and defects", there is a paragraph in the middle, I will knock in playing.

#include

#include

Using namespace std;

INT main () {char * S1 = "s1"; char * s2 = "s2"; char * r = static_cast (malloc (Strlen (S1) Strlen (S2) 1); if (! r) {cout << "Malloc Fail / N"; EXIT (-1);

STRCPY (R, S1); cout << r << endl; strcat (r, s2); cout << r << endl; free (r);}

This is the style of C, which is a C programmer, I can't help but change Malloc to new, free replacement delete, so there is such code: int main () {char * S1 = "s1"; char * S2 = "s2"; char * r = new char (Strlen (S1) Strlen (S2) 1); if (! r) {cout << "malloc fail / n"; exit (-1);

STRCPY (R, S1); COUT << r << endl; strcat (r, s2); cout << r << endl; delete r;}

Running, grace, as I mean, the output is:

S1S1S2

I don't know what I think at the time, I put: cout << r << Endl; changed: cout << "| << r <<" | / n "; 哐! Illegal operation! what happened? It took a long time bug, because illegal operations appeared after printing, I noticed the problem of Delete. No parentheses! New back a string of space, how do you get DELETE? Looking for death! Delete [] R; still have problems! Looking from the beginning, after a while, I finally seem to see what char * r = new char (Strlen (S1) Strlen (S2) 1); how do I be stupid! The value in parentheses is not required to return, but the initial value.

BUG will latency in the process, no sound, but when it jumps out, it is late ... The correct expression of the syntax can not rule out the correct expression of the semantic, can be compiled, the connection cannot rule out the error (nonsense).

In short, we must be carefully encoded.

New Type (Initial_Value) 2. New Type [Block_Size] 3. Of course there is a Placement New, not to mention.

转载请注明原文地址:https://www.9cbs.com/read-114956.html

New Post(0)