473,395 Members | 1,823 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,395 software developers and data experts.

pass by Reference/value ???

hi there
i m little bit confused over the following problem, i have understood wt the
following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its
pass by reference or pass by value...hope somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}

regards
Jul 22 '05 #1
14 3049
dumboo wrote:
hi there
i m little bit confused over the following problem, i have understood wt the
following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its
pass by reference or pass by value...hope somebody clears it up :-)
Well, the code is totally bogus and exhibits undefined behavior. If you
are lucky, it'll only crash.
void foo(char *s)
`foo()' is passed a pointer-to-char -- by value {
s = new char[10];
s -- the local copy of this pointer-to-char now points to enough memory
out of the free store to hold ten chars.
strcpy(s, "gotit");
The string literal "gotit" is copied into that memory.
}
And the local copy of `s' has gone out of scope, causing a memory leak.

int main()
{
char *s;
`s' is an uninitialized pointer-to-char that points to...well, *anywhere*,
foo(s);
`foo()' is called; however as it has been passed by value it is
unchanged, hence still uninitialized.
cout<<s;
An attempt is made to send the contents pointed to by `s' to the stream
`cout'. Since `s' points...well *anywhere*...undefined behavior is
invoked. [first time]
delete s;
An attempt to delete the memory pointed to by `s' is made. Since s is an
uninitialized pointer, undefined behavior is invoked. [second time]
return 0;
}

If you change the signature of `foo()' to:

void foo(char*& s)

you will get the behavior I would suspect you want.

HTH,
--ag
--
Artie Gold -- Austin, Texas

"Yeah. It's an urban legend. But it's a *great* urban legend!"
Jul 22 '05 #2
"dumboo" <vt***@yahoo.com> wrote in message
news:c0*************@ID-211285.news.uni-berlin.de...
hi there
i m little bit confused over the following problem, i have understood wt the following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its pass by reference or pass by value...hope somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}


Here you are passing a pointer by value.

Among other things, you need to delete s like so: delete [] s.

BTW, who having you been hotly debating?

Jonathan
Jul 22 '05 #3

"Jonathan Turkanis" <te******@kangaroologic.com> wrote in message
news:c0*************@ID-216073.news.uni-berlin.de...

Among other things, you need to delete s like so: delete [] s.

For the 'other things' see Artie's post ;-)
Jul 22 '05 #4

"dumboo" <vt***@yahoo.com> wrote in message
news:c0*************@ID-211285.news.uni-berlin.de...
hi there
i m little bit confused over the following problem, i have understood wt the
following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its
pass by reference or pass by value...hope somebody clears it up :-)
Didn't you try to run the program? Let's analyse the program line by line.
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s; s points to some garbage address. foo(s); Copy the garbage address contained in s to foo's s. This is pass-by-value.
Then in foo you make foo's copy of s to point to some valid dynamic store (heap)
address. Write something to it and then do a *memory leak* when you don't delete
what s points to. s gets destructed when function returns and the memory it
allocated is
never given back to the system. cout<<s; Now you return in main. Here s still points to the same garbage address it
pointed to before it entered foo.
You know now what you can expect from this program..right?
delete s; Now you try to free the memory pointed by s. But actaully s points to some
garbage address!
Also you should have done delete [] s;
return 0;
}


The easiest way to resolve this is by changing foo like -
void foo(char *& s)
Now when you change s within foo it gets reflected in main too.
This is pass-by-reference.

-Sharad
Jul 22 '05 #5
"dumboo" <vt***@yahoo.com> wrote in message
news:c0*************@ID-211285.news.uni-berlin.de
hi there
i m little bit confused over the following problem, i have understood
wt the following code is doing...but not able to get the actual
techinical stuff.....i have had a lot of hot debate over the
following code whether its pass by reference or pass by value...hope
somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}

regards

There is some confusion here resulting from C++'s origin in C. The C
language does not have C++-style references. Accordingly, if you want a
function in C to modify something, you need to pass it a pointer to the
thing to be modified. In C, this is called "passing by reference". Now
consider your function:

void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

In C, this would be called "passing by reference". The important thing to
note, however, is that the thing that is passed by reference is *not* the
variable s but what s points to, i.e., s is passed by value and what s
points to is passed by reference. What this means is that

1. foo receives a local copy of s and any changes that it makes to s only
affect that local copy.
2. the copy of s that foo receives points to the same memory area as the
original s did, so any changes made to what s points to have the same effect
within the function as they would have in the place from which the function
is called.

In your line:

s = new char[10];

you are changing the local copy of s, which has no effect on the original s.
Thus cout in main() is being applied to the uninitialised s.

If you want to modify s, then there are two ways to go about it. The C-style
approach is to pass the address of s rather than s itself, as follows:

void foo(char **ps)
{
*ps = new char[10];
strcpy(*ps, "gotit");
}

int main()
{
char *s;
foo(&s);
cout << s;
delete[] s;
return 0;
}

Note:

1. Since s is a pointer, a variable storing the address of s is a pointer to
pointer. Thus there is a double asterisk in the definition of foo's
parameter. ps is a pointer to s, so *ps gives the original s. Hence *ps
replaces s in your foo function.
2. foo is called with an argument of &s rather than with an argument of s.
3. I have changed your original delete to the (correct) array form of
delete[].

The C++-style approach is to use references as follows:

void foo(char *& s)
{
s = new char[10];
strcpy(s, "gotit");
}
int main()
{
char *s;
foo(s);
cout << s;
delete[] s;
return 0;
}

This involves the least change to your code. All you need to do is replace

void foo(char *s)

with

void foo(char *& s)

i.e., you only need add the & symbol. This change means that s itself ---
and not just what it points to --- is "passed by reference" (in the C++
sense of that term). This means that foo operates on the original s --- no
local copy is made --- so that any changes that foo makes to s affect the
original.
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)

Jul 22 '05 #6
hi there,
BTW, who having you been hotly debating?


hes my friend...student like me.. :-)
Jul 22 '05 #7
hi there,

"John Carson" <do***********@datafast.net.au> wrote in message
news:40******@usenet.per.paradox.net.au...
"dumboo" <vt***@yahoo.com> wrote in message
news:c0*************@ID-211285.news.uni-berlin.de
hi there
i m little bit confused over the following problem, i have understood
wt the following code is doing...but not able to get the actual
techinical stuff.....i have had a lot of hot debate over the
following code whether its pass by reference or pass by value...hope
somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}

regards

There is some confusion here resulting from C++'s origin in C. The C
language does not have C++-style references. Accordingly, if you want a
function in C to modify something, you need to pass it a pointer to the
thing to be modified. In C, this is called "passing by reference". Now
consider your function:

void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

In C, this would be called "passing by reference". The important thing to
note, however, is that the thing that is passed by reference is *not* the
variable s but what s points to, i.e., s is passed by value and what s
points to is passed by reference. What this means is that

1. foo receives a local copy of s and any changes that it makes to s only
affect that local copy.
2. the copy of s that foo receives points to the same memory area as the
original s did, so any changes made to what s points to have the same

effect within the function as they would have in the place from which the function is called.

In your line:

s = new char[10];

you are changing the local copy of s, which has no effect on the original s. Thus cout in main() is being applied to the uninitialised s.

If you want to modify s, then there are two ways to go about it. The C-style approach is to pass the address of s rather than s itself, as follows:

void foo(char **ps)
{
*ps = new char[10];
strcpy(*ps, "gotit");
}

int main()
{
char *s;
foo(&s);
cout << s;
delete[] s;
return 0;
}

Note:

1. Since s is a pointer, a variable storing the address of s is a pointer to pointer. Thus there is a double asterisk in the definition of foo's
parameter. ps is a pointer to s, so *ps gives the original s. Hence *ps
replaces s in your foo function.
2. foo is called with an argument of &s rather than with an argument of s.
3. I have changed your original delete to the (correct) array form of
delete[].

The C++-style approach is to use references as follows:

void foo(char *& s)
{
s = new char[10];
strcpy(s, "gotit");
}
int main()
{
char *s;
foo(s);
cout << s;
delete[] s;
return 0;
}

This involves the least change to your code. All you need to do is replace

void foo(char *s)

with

void foo(char *& s)

i.e., you only need add the & symbol. This change means that s itself ---
and not just what it points to --- is "passed by reference" (in the C++
sense of that term). This means that foo operates on the original s --- no
local copy is made --- so that any changes that foo makes to s affect the
original.
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)


thanks all the guys for the superb answer, got many of my concepts cleared
:-)
Jul 22 '05 #8
In article <40******@usenet.per.paradox.net.au>,
John Carson <do***********@datafast.net.au> wrote:

The C++-style approach is to use references as follows:

void foo(char *& s)
{
s = new char[10];
strcpy(s, "gotit");
}
int main()
{
char *s;
foo(s);
cout << s;
delete[] s;
return 0;
}


Or better yet, use C++'s standard 'string' data type. Then you don't have
to bother with char pointers and new and delete at all.

#include <iostream>
#include <string>

using namespace std;

void foo (string& s)
{
s = "gotit";
}

int main ()
{
string s;
foo (s);
cout << s;
return 0;
}

--
Jon Bell <jt*******@presby.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
Jul 22 '05 #9
I will like to say that references were introduced in c++ and the
prototype of the function u have given has been there since c. and the
prototype for with pass by reference is:
void foo(char *&s)
in above prototype s is passsed by refernece parameter.
regards

"dumboo" <vt***@yahoo.com> wrote in message news:<c0*************@ID-211285.news.uni-berlin.de>...
hi there
i m little bit confused over the following problem, i have understood wt the
following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its
pass by reference or pass by value...hope somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}

regards

Jul 22 '05 #10
Jonathan Turkanis wrote:

"dumboo" <vt***@yahoo.com> wrote in message
news:c0*************@ID-211285.news.uni-berlin.de...
hi there
i m little bit confused over the following problem, i have

understood wt the
following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code

whether its
pass by reference or pass by value...hope somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}


Here you are passing a pointer by value.

Among other things, you need to delete s like so: delete [] s.


That just somewhat different undefined behavior to the undefined
behavior he already has due to his faulty allocation.

The pointer back in main is unaffected by the new over in foo(). So
deferencing it in main() via the cout is undefined. The delete is wrong,
but so is using delete[] on an uninitialized pointer.

The function foo() either needs to take a char** or return a char*.

Brian Rodenborn
Jul 22 '05 #11
John Carson wrote:
If you want to modify s, then there are two ways to go about it. The C-style
approach is to pass the address of s rather than s itself, as follows:

void foo(char **ps)
{
*ps = new char[10];
strcpy(*ps, "gotit");
} The C++-style approach is to use references as follows:

void foo(char *& s)
{
s = new char[10];
strcpy(s, "gotit");
}

A third way is to return a pointer, like so:

char* foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
return s;
}
Brian Rodenborn
Jul 22 '05 #12
> > hi there
i m little bit confused over the following problem, i have understood wt the
following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its
pass by reference or pass by value...hope somebody clears it up :-)

int main()
{
char *s;


`s' is an uninitialized pointer-to-char that points to...well, *anywhere*,
foo(s);


`foo()' is called; however as it has been passed by value it is
unchanged, hence still uninitialized.
cout<<s;


An attempt is made to send the contents pointed to by `s' to the stream
`cout'. Since `s' points...well *anywhere*...undefined behavior is
invoked. [first time]


Second time, actually; foo(s) is UB because it evaluates s
(it could be a trap value).
Jul 22 '05 #13
"Default User" <fi********@boeing.com.invalid> wrote in message
news:40***************@boeing.com.invalid

A third way is to return a pointer, like so:

char* foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
return s;
}


In which case no use is being made of the argument passed except as a source
of a local variable, so it would be simpler to use:

char* foo()
{
char *s = new char[10];
strcpy(s, "gotit");
return s;
}
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)

Jul 22 '05 #14

"Default User" <fi********@boeing.com.invalid> wrote in message
news:40***************@boeing.com.invalid...
John Carson wrote:
If you want to modify s, then there are two ways to go about it. The C-style
approach is to pass the address of s rather than s itself, as follows:

void foo(char **ps)
{
*ps = new char[10];
strcpy(*ps, "gotit");
}

The C++-style approach is to use references as follows:

void foo(char *& s)
{
s = new char[10];
strcpy(s, "gotit");
}

A third way is to return a pointer, like so:

char* foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
return s;
}


For a simple program like this, it's fine.
But atleast in a library I would not like this approach.
This would mean that you need to tell your users that the responsibility to free
the memory is with you.
Unless one is quite careful with such libraries there are bound to be potential
memory leaks.

-Sharad
Jul 22 '05 #15

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

Similar topics

5
by: Seeker | last post by:
Newbie question here... I have a form with some radio buttons. To verify that at least one of the buttons was chosen I use the following code ("f" is my form object) : var btnChosen; for...
110
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object...
4
by: z_learning_tester | last post by:
I'm reading the MS press C# book and there seems to be a contradiction. Please tell me which one is correct, 1 or 2. Thanks! Jeff 1. First it gives the code below saying that it prints 0 then...
5
by: David++ | last post by:
Hi folks, I would be interested to hear peoples views on whether or not 'pass by reference' is allowed when using a Web Service method. The thing that troubles me about pass-by-reference into...
4
by: Jon Slaughter | last post by:
I'm reading a book on C# and it says there are 4 ways of passing types: 1. Pass value type by value 2. Pass value type by reference 3. Pass reference by value 4. Pass reference by reference. ...
14
by: Abhi | last post by:
I wrote a function foo(int arr) and its prototype is declared as foo(int arr); I modify the values of the array in the function and the values are getting modified in the main array which is...
4
by: kinaxx | last post by:
Hello, now I'm learning progamming language in university. but i have some question. in textbook. says there are four passing Mechanism 1) pass by value (inother words : call by value) 2)...
10
by: Robert Dailey | last post by:
Hi, I noticed in Python all function parameters seem to be passed by reference. This means that when I modify the value of a variable of a function, the value of the variable externally from the...
6
by: lisp9000 | last post by:
I've read that C allows two ways to pass information between functions: o Pass by Value o Pass by Reference I was talking to some C programmers and they told me there is no such thing as...
12
by: raylopez99 | last post by:
Keywords: scope resolution, passing classes between parent and child forms, parameter constructor method, normal constructor, default constructor, forward reference, sharing classes between forms....
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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,...

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.