473,770 Members | 1,989 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Another dynamic memory doubt

Hello friends:

I have the following code,

char* MyClass::MyMeth od()
{
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.
Jun 27 '08 #1
31 1199
On 26 Apr 2008 at 9:46, pradeep wrote:
I have the following code,
There are several problems and misunderstandin gs in your code...
char* MyClass::MyMeth od()
In C++, it's usually better to #include <stringand 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::MyMeth od()
{
return "hello";
}

Jun 27 '08 #2
pradeep wrote:
Hello friends:

I have the following code,

char* MyClass::MyMeth od()
This is C++. There is a dedicated group for C++ called comp.lang.c++.
Try that.

<snip>

Jun 27 '08 #3
pradeep wrote:
Hello friends:

I have the following code,

char* MyClass::MyMeth od()
^^^^^^^^ 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 <news:comp.lang .c++>.

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.
Jun 27 '08 #4
Antoninus Twink wrote:
On 26 Apr 2008 at 9:46, pradeep wrote:
>I have the following code,

There are several problems and misunderstandin gs 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.

Jun 27 '08 #5
In article <fu**********@a ioe.org>, pradeep <no****@nospam. comwrote:
>I have the following code,
>char* MyClass::MyMeth od()
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.
--
"History is a pile of debris" -- Laurie Anderson
Jun 27 '08 #6

"pradeep" <no****@nospam. comwrote in message news:fu******** **@aioe.org...
Hello friends:

I have the following code,

char* MyClass::MyMeth od()
{
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?
You want C++, next door.
However most programming languages have the feature that statements after a
return are not executed. The answer is to put those statements in the
calling code.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 27 '08 #7
Antoninus Twink <no****@nospam. invalidwrites:
On 26 Apr 2008 at 9:46, pradeep wrote:
>I have the following code,
char* MyClass::MyMeth od()

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)).

--
Ben.
Jun 27 '08 #8

"Richard" <de***@gmail.co mwrote in message
news:fu******** **@registered.m otzarella.org.. .
ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
>In article <fu**********@a ioe.org>, pradeep <no****@nospam. comwrote:
>>>I have the following code,
>>>char* MyClass::MyMeth od()

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.

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.
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++"?

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 27 '08 #9
On 26 Apr 2008 at 11:39, Ben Bacarisse wrote:
Antoninus Twink <no****@nospam. invalidwrites:
>In C++, ...

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.

Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
5223
by: fivelitermustang | last post by:
Actually, how would I go about allocating a four-dimensional dynamic array? I only know how to make two dimensional dynamic arrays: double **v; v = new double*; for (int i=0; i<C; i++) { v = new double; }
6
8213
by: chris | last post by:
Hi all, I need to know, what is the difference between dynamic memory allocation, and stack allocation ? 1. If I have a class named DestinationAddress, when should I use dynamic memory allocation to create object of that class ? 2. If it says "dynamic memory allocation", is it mean the following code : DestinationAddress* dest = new DestinationAddress(); // code 1
21
2287
by: Marky C | last post by:
atof is not working. double a = atof("12.345"); a gets set to 12.000 I am working on a toshiba micro. The data map has no space allocated to it for dynamic memory. Does anyone have an idea? Could it be due to the lack of dynamic
10
2782
by: s.subbarayan | last post by:
Dear all, I happen to come across this exciting inspiring article regarding memory leaks in this website: http://www.embedded.com/story/OEG20020222S0026 In this article the author mentions: "At a certain point in the code you may be unsure if a particular block is no longer needed. If you free() this piece of memory, but continue to access it (probably via a second pointer to the same
3
1312
by: Stephen Gennard | last post by:
Hello, I having a problem dynamically invoking a static method that takes a reference to a SByte*. If I do it directly it works just fine. Anyone any ideas why? I have include a example below... --
24
19094
by: Ken | last post by:
In C programming, I want to know in what situations we should use static memory allocation instead of dynamic memory allocation. My understanding is that static memory allocation like using array is faster than malloc, but dynamic memory allocation is more flexible. Please comment... thanks.
1
7976
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was compiled and run without any erros but the second program has a run time error when the function return from allocate and the ptr become NULL. How to fixed this? Second Program: /* Best Method to allocate memory for 2D Array because it's ...
14
3837
by: vivek | last post by:
i have some doubts on dynamic memory allocation and stacks and heaps where is the dynamic memory allocation used? in function calls there are some counters like "i" in the below function. Is this stored in stack. If yes whether it will be deleted on exiting from the function. is dynamic memory allocation needed for this purpose
6
1676
by: anuvanand1 | last post by:
I am writing a program for portable devices hence memory management is a big constraint. To my knowledge only if u free the dynamically allocated memory it can be used further.. My doubt is I have a function which is returing a pointer. pointer is dynamically allocated .....if I free the pointer before returning then it is useless or dangling pointer problem arises....or if I free after returning the ptr the control is...
0
9618
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10259
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9906
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.