This is my code. I create a char array and assign a string literal to it by operator=. After which, I free it by delete.However, it cause segmentation. But it works fine with strcpy. Besides, Is char array always assigned by strcpy?
I got to this problem from Implementaion of STL std::string, I wonder why private char* _data
is always assigned by strcpy, can't it assign by operator=?
since char* A= "HELLO WORLD"
works as well.
int main()
{
char* a=new char[3];
a="12";
//strcpy(a,"aa");
delete[] a;
}
You can only delete[]
something that you allocate with new[]
.
So this code is OK, because a
points to memory you allocated with new[]
int main()
{
char* a = new char[3];
delete[] a;
}
This code is also OK, because a
is still pointing at memory allocated with new[]
int main()
{
char* a=new char[3];
strcpy(a, "aa"); // this doesn't change a
delete[] a;
}
But this code is different. In this code a
starts pointing at memory allocated with new[]
but then you change the pointer. You make a
point at "aa"
. That is not memory allocated with new[]
and so you get a crash.
int main()
{
char* a=new char[3];
a = "aa"; // this does change a
delete[] a;
}
The difference between the second and third version, is that the second version changes the characters that a
is pointing at, but the third version changes the pointer a
itself. That's the crucial difference.
When you work with pointers you must understand the difference between changing the pointer and changing whatever the pointer is pointing at. These are two different things.