gallows wrote:
In this code:
void f()
{
char* s1 = new char;
allocates a single character.
s1 = "fred";
memory leak. You've lost the pointer you allocated with new, s2 now
points to the first character of the string literal "fed".
>
char* s2 = new char[4];
you've allocated four characters.
s2 = "fred";
memory leak. You've lost the pointer you allocated with new, s2 now
points to the first character of the string literal "fred".
}
What is the difference between s1 and s2?
When I should use new[]?
You want to use new[] when you allocate multiple items.
Why if I append "delete[] s1" I get: "*** glibc detected *** ./foo:
free(): invalid pointer: 0x0804874c ***" ?
Because s1 is not allocated with new[], it isn't even allocated anymore,
it's pointing to a string literal.
>
I know that seems stupid, but it's not clear for me.
Thanks.
You're better off not using new and delete for this. Use std::string,
or std::vector.