473,403 Members | 2,293 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

Confuse with local char*

i have a function as listed below:

char* ltoa(char* chr)
{
char* myChr=new char[100];
strcpy(myChr,chr);
return myChr;
}

in the above code i am returning a reference or pointer to a local
variable. Still how come i am getting the expected string in the caller
function of this function. It should print some junk characters. Now ,
I know memory for "myChr" has been allocated from heap. Now, if that is
the reason why I am getting the desired string then how can I allocate
some memory for this "myChr" in local stack so that I get junk chars
when I print the returned string in my caller function of ltoa()?

Jul 23 '05 #1
3 1605

----- Original Message -----
From: <am*********@gmail.com>
Newsgroups: comp.lang.c++
Sent: Saturday, July 02, 2005 2:26 PM
Subject: Confuse with local char*

i have a function as listed below:

char* ltoa(char* chr)
{
char* myChr=new char[100];
strcpy(myChr,chr);
return myChr;
}

in the above code i am returning a reference or pointer to a local
variable. Still how come i am getting the expected string in the caller
function of this function. It should print some junk characters. Now ,
I know memory for "myChr" has been allocated from heap. Now, if that is
the reason why I am getting the desired string then how can I allocate
some memory for this "myChr" in local stack so that I get junk chars
when I print the returned string in my caller function of ltoa()?


Actually, you never called delete on myChr. That's why it survives.
Basically the memory that myChr is pointing to is going to survive
until you call delete on it.

Now, if you did:
char myChr[100];
strcpy(myChr,chr);
return myChr;

the memory myChr is pointing to would be cleaned up as soon as
the function line ended.

That is (using my code, not yours):

std::cout << ltoa("Test") << std::endl;
would print Test.

char* temp = ltoa("Test");
std::cout << temp << std::endl;

would probably print junk.

But with your new allocation, either would print "Test".
Jul 23 '05 #2
On Sat, 02 Jul 2005 14:26:13 -0700, ambar.shome wrote:
i have a function as listed below:

char* ltoa(char* chr)
{
char* myChr=new char[100];
strcpy(myChr,chr);
return myChr;
}

in the above code i am returning a reference or pointer to a local
variable. Still how come i am getting the expected string in the caller
function of this function. It should print some junk characters. Now ,
I know memory for "myChr" has been allocated from heap. Now, if that is
the reason why I am getting the desired string then how can I allocate
some memory for this "myChr" in local stack so that I get junk chars
when I print the returned string in my caller function of ltoa()?


Pointers are variables that hold addresses. They know nothing else about
the memory they point to, which can live way longer (until deleted) than
the pointer itself. It's important that you pass that address from one
function to another, and you don't lose it.

char * myChr is the variable that holds the ADDRESS of the memory you
allocate with new. The address that myChr holds is passed to the calling
function via the return myChr statement. Then myChr can die quietly and
peacefully, happy to fulfill its destiny. Nothing happens to the actual
buffer allocated with new. It outlives the function that allocated it
(until explicitly deleted) and its address (previously held by myChar) is
now in the hands of the calling function, which can do useful work on that
buffer.

Jul 23 '05 #3
Le samedi 2 juillet 2005 à 23:26:13, am*********@gmail.com a écrit dans
comp.lang.c++*:
i have a function as listed below:

char* ltoa(char* chr)
{
char* myChr=new char[100];
strcpy(myChr,chr);
return myChr;
}

in the above code i am returning a reference or pointer to a local
variable.


No, you're not. The only local variable is 'myChr' and you're not
returning a reference nor a pointer to 'myChr'; you're returning the
content of 'myChr', that is a pointer to some dynamically allocated
memory.

You'll need to call delete[] on that pointer at some point to avoid
memory leak:

char *p = ltoa("123");
// do something with p...
delete[] p;
--
___________ 03/07/2005 09:36:06
_/ _ \_`_`_`_) Serge PACCALIN -- sp ad mailclub.net
\ \_L_) Il faut donc que les hommes commencent
-'(__) par n'être pas fanatiques pour mériter
_/___(_) la tolérance. -- Voltaire, 1763
Jul 23 '05 #4

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

Similar topics

11
by: Alzane | last post by:
I'm new to C++ programming. I have an exercise that I have written code for but getting warnings. Can I get some help? #include "stdafx.h" #include <string.h> #include <stdio.h> #include...
26
by: bahadir.balban | last post by:
Hi, When you define varibles in the middle of your function call (C99), such as: if(i == 5) { int x = 5; int z = 2; }
5
by: akarui.tomodachi | last post by:
I have about twenty functions written in C. Each time I call a function, it logs the status of the function operation to a file. I use a central logging function which is called from each function...
5
by: FireHead | last post by:
Hello All, Its hard to explain but here it goes: char &free_malloc(char* object_copy){ Here ------------------------------------------------------------------ object_copy is parametre were...
2
by: Filip Konvicka | last post by:
Hi all, I wonder whether anyone has seen a workaround for this somewhere, perhaps in Boost or elsewhere... I succeeded using a local type as template argument in MSVC 8.0, but I found out...
10
by: Jess | last post by:
Hello, If a function that returns an array of char like this one: const char* f(){ return "abc"; } then is the char array "abc" local/temporary object? I thought it should be temporary...
13
by: hari | last post by:
Hi all, Is it legal to return a local variable from function. Regards Hari
25
by: dpapathanasiou | last post by:
I have some old Common Lisp functions I'd like to rewrite in Python (I'm still new to Python), and one thing I miss is not having to declare local variables. For example, I have this Lisp...
4
by: raylopez99 | last post by:
Why is the same variable local inside a 'foreach' loop yet 'global' in scope (or to the class) outside it? RL class MyClass { int MyMemberArray1; //member variables, arrays, that are...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.