Questions on dynamic allocation

G

gallows

In this code:

void f()
{
char* s1 = new char;
s1 = "fred";

char* s2 = new char[4];
s2 = "fred";
}

What is the difference between s1 and s2?
When I should use new[]?
Why if I append "delete[] s1" I get: "*** glibc detected *** ./foo:
free(): invalid pointer: 0x0804874c ***" ?

I know that seems stupid, but it's not clear for me.
Thanks.

s.
 
R

red floyd

gallows said:
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.
 
G

gallows

-- snip --
Because s1 is not allocated with new[], it isn't even allocated anymore,
it's pointing to a string literal.

Oh, _now_ it's clear. Thanks.
You're better off not using new and delete for this. Use std::string,
or std::vector.

I will do, thanks.
 
R

red floyd

gallows said:
-- snip --
Because s1 is not allocated with new[], it isn't even allocated anymore,
it's pointing to a string literal.

Oh, _now_ it's clear. Thanks.
You're better off not using new and delete for this. Use std::string,
or std::vector.

I will do, thanks.

You're welcome. I hope my explanation was moderately clear -- I usually
start out with an idea of what I want to explain, but fail miserably. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top