The program crashes because you aren't delete[]
'ing the pointer you allocated with new[]
.
char* source;
source = new char[20];
source = "Hello";
delete[] source;
You first assign source
to a dynamic array of 20 chars, but then you change source
to point at a string literal. A string literal isn't allocated with new[]
, so delete[]
'ing it crashes the program.
I suppose that when you wrote source = "Hello";
what you were trying to do was copy the characters of "Hello"
into the location pointed at by source
, but that's not what that line of code actually does. It copies the pointer, not what is being pointed at.
Here's one way of correcting the code:
strcpy(source, "Hello");
This would also work:
memcpy(source, "Hello", 5+1); // +1 for null terminator
Both of these functions copy the characters, not the pointer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…