Another dynamic memory doubt

P

pradeep

Hello friends:

I have the following code,

char* MyClass::MyMethod()
{
char* ptr = new char[6]; // space for NULL terminator
ptr = "hello";
return ptr;
delete[] ptr;
}

What I'm trying to do is return ptr, but delete[] it afterwards. In the
code above, I believe the delete[] line will not be executed following
the return statement.

How should I achieve this?

Thanks.
 
A

Antoninus Twink

I have the following code,

There are several problems and misunderstandings in your code...
char* MyClass::MyMethod()

In C++, it's usually better to #include <string> and then use
std::string instead of C-style strings. You can always get a good old
char * back if necessary by using the c_str() method.
{
char* ptr = new char[6]; // space for NULL terminator
ptr = "hello";

This does not copy the string "hello" into the array you've just
allocated, but rather makes ptr point to the start of a string literal,
which will be stored in the data segment of your object file.

A consequence of this is that you have leaked the memory you allocated
on the line before, and trying to delete ptr will cause problems.
return ptr;
delete[] ptr;
}

What I'm trying to do is return ptr, but delete[] it afterwards. In the
code above, I believe the delete[] line will not be executed following
the return statement.

Of course not! A return statement moves you up a stack frame, and in
particular sets the program counter to where it was when you called the
function.
How should I achieve this?

In the documentation for your function, explain that it allocates some
memory and that the caller is responsible for deleting ptr.

Or don't allocate memory at all, but just have

char* MyClass::MyMethod()
{
return "hello";
}
 
S

santosh

pradeep said:
Hello friends:

I have the following code,

char* MyClass::MyMethod()

This is C++. There is a dedicated group for C++ called comp.lang.c++.
Try that.

<snip>
 
M

Martin Ambuhl

pradeep said:
Hello friends:

I have the following code,

char* MyClass::MyMethod()

^^^^^^^^ This line is a syntax error in C.
{
char* ptr = new char[6]; // space for NULL terminator
^^^^^^^^ This line is a syntax error in C.
ptr = "hello";

^^^^^^^^ If the preceding non-C line allocated space for a char[6] and
assigned the address of the first element to ptr, then
this line creates a memory leak and loses the address of
the char[6] array.
return ptr;
delete[] ptr;
^^^^^^^^ This line is a syntax error in C, and even if it weren't,
the return in the line before makes this line unreachable.
}

What I'm trying to do is return ptr, but delete[] it afterwards.

In the foolish language you are grossly misusing, you will need to
delete the array separately. However, since you have assigned the
addess of the anonymous char literal "hello" to ptr, that is almost
guaranteed to blow up in your face. After you go back and read your
textbook and read the FAQ for the newsgroup for the language you are
using, ask in that newsgroup. It is very likely that the language you
are misusing in C++, and its newsgroup is <
In the
code above, I believe the delete[] line will not be executed following
the return statement.

How should I achieve this?

By not coding randomly and praying that whatever you type is legal. Put
some effort into actually learning the language.
 
S

santosh

Antoninus said:
There are several problems and misunderstandings in your code...

<snip C++ code and response>

Nowhere in your post did you mention to the OP that there is in fact a
dedicated Usenet group for C++ where answers are likely to be more
correct than OT responses in other groups. Why is that? Do you
deliberately want the OP to remain ignorant of the best forum for help
with his problem and risk betting on possibly incorrect or outdated
advice in other groups?

Answering questions on non-conforming C code is one thing but answering
questions on totally separate languages and other wildly OT matters
(like the recent thread on Ethernet cables) seems a deliberate tactic
to lower the S:N ratio and wreck this group.
 
W

Walter Roberson

I have the following code,
char* MyClass::MyMethod()

That line is a syntax error. The only place that a colon (':')
can occur in a type description in C is as a bit-field length
within a structure definition.
{
char* ptr = new char[6]; // space for NULL terminator

That line is a syntax error. There is no storage class named 'new'
in C.
ptr = "hello";
return ptr;
delete[] ptr;

Another syntax error.
}

What I'm trying to do is return ptr, but delete[] it afterwards. In the
code above, I believe the delete[] line will not be executed following
the return statement.
How should I achieve this?

How can you be assured that the pointer would not be deleted until
after the calling routine had finished accessing the data??
If you create storage and return a pointer to that storage, you cannot
also delete that storage, not unless the calling routine will never
attempt to access the storage nor to test the pointer against anything
other than a null pointer constant.

One would suspect that your code is not in fact C code, in
which case our most charitable assumption would be that you
have -accidently- posted your question to the wrong newsgroup.

But even if so, you need to figure out what it is supposed to
mean to delete a pointer to a storage area when you have returned
that pointer outwards. There are not many languages around
(-none- that I can think of right now) in which returning a pointer
to a memory block is understood to mean that the procedure
calling mechanism should take a -copy- of the storage pointed to
and put that copy somewhere for future use.
 
B

Ben Bacarisse

Antoninus Twink said:
In C++, ...

I won't point out the C++ errors you made (that would be to fall into
your trap) but the original poster should know:

(a) that comp.lang.c++ is the place to ask;
(b) answers here will not checked by people who really know C++;
(c) your answer was not correct (IMO, but see (b)).
 
R

Richard

I have the following code,
char* MyClass::MyMethod()

That line is a syntax error. The only place that a colon (':')
can occur in a type description in C is as a bit-field length
within a structure definition.
{
char* ptr = new char[6]; // space for NULL terminator

That line is a syntax error. There is no storage class named 'new'
in C.
ptr = "hello";
return ptr;
delete[] ptr;

Another syntax error.
}

What I'm trying to do is return ptr, but delete[] it afterwards. In the
code above, I believe the delete[] line will not be executed following
the return statement.
How should I achieve this?

How can you be assured that the pointer would not be deleted until
after the calling routine had finished accessing the data??
If you create storage and return a pointer to that storage, you cannot
also delete that storage, not unless the calling routine will never
attempt to access the storage nor to test the pointer against anything
other than a null pointer constant.

One would suspect that your code is not in fact C code, in
which case our most charitable assumption would be that you
have -accidently- posted your question to the wrong newsgroup.

But even if so, you need to figure out what it is supposed to
mean to delete a pointer to a storage area when you have returned
that pointer outwards. There are not many languages around
(-none- that I can think of right now) in which returning a pointer
to a memory block is understood to mean that the procedure
calling mechanism should take a -copy- of the storage pointed to
and put that copy somewhere for future use.

It amazed me that there are already about 5 people who have told him
this is C++ code and yet you feel the need to go lengths to belittle the
OP.

You did know there had been OT replies. You did know that it was
C++. One can only guess at your motives for posting such a long and
relatively useless reply.
 
A

Antoninus Twink

I won't point out the C++ errors you made (that would be to fall into
your trap)

If there were real errors (not just the usual not standard, not portable
bullshit) then point them out and cross-post to clc++ if you insist.
 
R

Richard

Malcolm McLean said:
Unfortunately Walter's sort of reply - and we can all be clever Dicks
to people new to programming - encourages people like Antonius Twink
to give off-topic answers as a sort of compensation.
Why can't people just say "this is C++"?

or why not post nothing at all when they KNOW Santosh, Falconer or Default Luser
will correct them.
 
B

Ben Bacarisse

Antoninus Twink said:
If there were real errors (not just the usual not standard, not portable
bullshit) then point them out and cross-post to clc++ if you insist.

There is nothing stopping you posting your code in comp.lang.c++ and
there is nothing I can do to stop you if you choose to do something so
daft as cross-posting C++ code in both groups, but you can't sucker me
into doing it for you.
 
A

Antoninus Twink

<snip C++ code and response>

Nowhere in your post did you mention to the OP that there is in fact a
dedicated Usenet group for C++ where answers are likely to be more
correct than OT responses in other groups. Why is that? Do you
deliberately want the OP to remain ignorant of the best forum for help
with his problem and risk betting on possibly incorrect or outdated
advice in other groups?

There is never any shortage of people who point out "more appropriate
groups" (usually with considerable bile and hostility, but
that's by the by).
Answering questions on non-conforming C code is one thing but answering
questions on totally separate languages and other wildly OT matters
(like the recent thread on Ethernet cables) seems a deliberate tactic
to lower the S:N ratio and wreck this group.

Here are some of the things I discussed with my colleagues at lunch
yesterday: C programming; Java programming; tree data structures; a
problem with someone's car; the new Ubuntu release; national politics. I
can promise you that my group hasn't been "wrecked" by this terrible
"lowering of the S:N ratio". On the contrary, in real life discussions
are eclectic by their nature, and talking about other things besides the
intricate minutiae of the C standard actually help build a positive
community, and that's good for exchanging programming knowledge too.
 
S

santosh

Antoninus said:
On 26 Apr 2008 at 10:24, santosh wrote:


Here are some of the things I discussed with my colleagues at lunch
yesterday: C programming; Java programming; tree data structures; a
problem with someone's car; the new Ubuntu release; national politics.
I can promise you that my group hasn't been "wrecked" by this terrible
"lowering of the S:N ratio".

Why are you comparing a face-to-face group discussion with a newsgroup?
They are totally different beyond the basic fact that both are used for
exchange of ideas.
On the contrary, in real life discussions
^^^^^^^^^^
<snip>

So anything further you say has no bearing for a newsgroup.

As I said, answering non-standard C questions is one thing but answering
questions on everthing under the Sun is only going to encourage newbies
and lurkers to start posting OT and drown the topical content.

There is also the fact that non-C answers are likely to have lower rate
of correctness, and this combined with deliberately concealing from the
newbie the existence of a dedicated group and inviting him to post
further non-C questions here is a disservice not only to the group
(which I understand that you don't like) but also to the newbie.
are eclectic by their nature, and talking about other things besides
the intricate minutiae of the C standard actually help build a
positive community, and that's good for exchanging programming
knowledge too.

No. Newsgroups are not communities. They are places to ask questions and
air ideas on the specified topic and receive responses. They don't
function like real-life informal communities or groups. They can be
better compared to a real-life support group. Do you also go to
Alcoholics Anonymous and complain of your C problems?
 
R

Richard

Default User said:
santosh said:
Antoninus Twink wrote:
[]

Why are you comparing a face-to-face group discussion with a
newsgroup?

Please don't feed the trolls.




Brian

Please do not wake up dead threads with your unnecessary net nannying.
 
W

Walter Roberson

Richard said:
It amazed me that there are already about 5 people who have told him
this is C++ code and yet you feel the need to go lengths to belittle the
OP.

Check out the postings times on the messages. My message was in
composition while the other (shorter) messages were sent.
You did know that it was C++.

I do *not* know that it was C++. It did -look- sort of like C++,
but there are other languages that look like C++ as well. For
example, I don't know enough C# to be able to tell C++ apart from C#.
 
W

Walter Roberson

Malcolm McLean said:
Unfortunately Walter's sort of reply

"sort of reply"? I am the only one who dealt with the fundamental
issue of storage lifetimes and wanting to delete a storage area
while it was still live.
 
W

Walter Roberson

Malcolm McLean said:
This is clever Dickery, or to use a more accurate term, disingenuous.

What, did I forget a case? Hmmm, I guess I did -- a ':' could occur
as part of a :? operation on compile-time constants that were
designating an array size. Okay, so perhaps that part was
"non-ingenuous" in that it was lacking the genius to create the
second case. But "disingenuous" implies an attempt to mislead,
whereas my reply was an attempt to set the OP straight.
 
O

Old Wolf

This does not copy the string "hello" into the array you've just
allocated, but rather makes ptr point to the start of a string literal,
which will be stored in the data segment of your object file.

Just stick to your trolling, and let the people who
actually know anything about C answer the questions.
It'll be less painful for all of us, believe me.
 
J

jacob navia

Old said:
Just stick to your trolling, and let the people who
actually know anything about C answer the questions.
It'll be less painful for all of us, believe me.

That's why you have (and should) remain silent. You know nothing
about C. All C implementations have a data segment.

All initial values of tables or numbers are stored there.
 

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
474,143
Messages
2,570,822
Members
47,368
Latest member
michaelsmithh

Latest Threads

Top