473,749 Members | 2,384 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Confuse with local char*

i have a function as listed below:

char* ltoa(char* chr)
{
char* myChr=new char[100];
strcpy(myChr,ch r);
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 1620

----- Original Message -----
From: <am*********@gm ail.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,ch r);
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,ch r);
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,ch r);
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*********@gma il.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,ch r);
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
11813
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 <stdlib.h>
26
2875
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
2232
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 to report status into a log file. However, I am using "sprintf" and formatting the log info into a string and sending to my central logging routine myLogFunc(). Here is the skeleton code: /*******************
5
2257
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 the contents of the malloc object in main driver module is copied. Which would mean that if I free the object_copy it should not effect
2
3299
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 that this violates the standard (14.3.1.2), and sadly does not work with g++ (3.4.3, did not try newer). I was essentialy able to run some code for each local type before main() - see the source code below.
10
2285
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 and hence the returned pointer should point to an
13
13200
by: hari | last post by:
Hi all, Is it legal to return a local variable from function. Regards Hari
25
1649
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 function: (defun random-char () "Generate a random char from one of " (if (< 50 (random 100)) (code-char (+ (random 10) 48)) ; ascii 48 = 0
4
2623
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 "global" to the class
0
8996
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
8832
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
9566
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
9388
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8256
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6800
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6078
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
4608
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...
3
2217
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.