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

Wrong way to pass pointer by value in functions

Hi,

I am still struggling to master C++ and is trying to understand how to
achieve passing arguments using pointers. I got some questions that I
like to post to the experts here, hope you can help to clarify my
doubts. I'm using g++ version 3.3.4. I created 3 classes as below for
testing some concepts. The questions are written as comments in
Bclass.h file. Thank you for your time and tips!

------------runtime errors------------
{8=> main
Aclass created.
Bclass instantiated.
main: Aclass.h:19: void Aclass::test(): Assertion `b' failed.
Aborted
-------------file: main.cc------------
#include "Aclass.h"

int main(){
Aclass a;
a.test();
}

-------------file: Aclass.h-----------
#ifndef ACLASS_H
#define ACLASS_H

#include "Bclass.h"
#include <stack>
#include <cassert>

class Aclass{
public:
Aclass(){
std::cout << "Aclass created." << std::endl;
}
~Aclass(){ std::cout << "Aclass destructed." << std::endl; }

void test(){
Bclass *b=NULL;
if( box.empty() ){
create(b);
assert(b); // As expected this fails during runtime
/* Qn: Is the failure because pointer 'b' is pointing to NULL?
* Qn: Is the reason why the call to "create" function without effect
* because the local pointer 'ptr' was changed to point to a temporary
object?
*/
}
delete b;
}

protected:
void create(Bclass *ptr){
box.push( new Bclass() );
ptr = box.top();
box.pop();// memory is pop
assert(ptr); // this is fine
/* Qn: Is the reason the assertion pass because local pointer 'b' is
* still referencing the memory?
* Qn: Is the memory release or considered unreferenced only if
* we get out of the "create" function?
*/
}

private:
std::stack<Bclass* > box;
};

#endif

-------------file: Bclass.h-----------
#ifndef BCLASS_H
#define BCLASS_H
#include <iostream>

class Bclass{
public:
Bclass(){ std::cout << "Bclass instantiated." << std::endl; }
~Bclass(){ std::cout << "Bclass destroyed." << std::endl; }
};
#endif

Jul 23 '05 #1
5 1909

"DamonChong" <so********@excite.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Hi,

I am still struggling to master C++ and is trying to understand how to
achieve passing arguments using pointers. I got some questions that I
like to post to the experts here, hope you can help to clarify my
doubts. I'm using g++ version 3.3.4. I created 3 classes as below for
testing some concepts. The questions are written as comments in
Bclass.h file. Thank you for your time and tips!

------------runtime errors------------
{8=> main
Aclass created.
Bclass instantiated.
main: Aclass.h:19: void Aclass::test(): Assertion `b' failed.
Aborted
-------------file: main.cc------------
#include "Aclass.h"

int main(){
Aclass a;
a.test();
}

-------------file: Aclass.h-----------
#ifndef ACLASS_H
#define ACLASS_H

#include "Bclass.h"
#include <stack>
#include <cassert>

class Aclass{
public:
Aclass(){
std::cout << "Aclass created." << std::endl;
}
~Aclass(){ std::cout << "Aclass destructed." << std::endl; }

void test(){
Bclass *b=NULL;
if( box.empty() ){
create(b);
assert(b); // As expected this fails during runtime
/* Qn: Is the failure because pointer 'b' is pointing to NULL?
Yes.
* Qn: Is the reason why the call to "create" function without effect
* because the local pointer 'ptr' was changed to point to a temporary
object?
Yes.
*/
}
delete b;
}

protected:
void create(Bclass *ptr){
box.push( new Bclass() );
ptr = box.top();
box.pop();// memory is pop
assert(ptr); // this is fine
/* Qn: Is the reason the assertion pass because local pointer 'b' is
* still referencing the memory?
It passes because ptr is pointing to valid memory. There is no b here.
* Qn: Is the memory release or considered unreferenced only if
* we get out of the "create" function?


It's a memory leak, because you created it with new, but never delete it.

If you want to modify something, you need to pass it by reference or via a
pointer. This includes modifying pointers themselves. So you need to pass
the pointer by reference (or via a pointer-to-pointer). Try:

void create(Bclass* &ptr) {...

-Howard


Jul 23 '05 #2

"Howard" <al*****@hotmail.com> wrote in message
news:xg********************@bgtnsc05-news.ops.worldnet.att.net...
* Qn: Is the reason why the call to "create" function without effect
* because the local pointer 'ptr' was changed to point to a temporary
object?


Yes.


Actually, that wasn't a correct response on my part. The pointer ptr is a
local copy (of the pointer b) in the create function. That copy was
assigned a value. But b itself was left unchanged, so it remained NULL.

-Howard

Jul 23 '05 #3

DamonChong wrote:
Hi,

I am still struggling to master C++ and is trying to understand how to achieve passing arguments using pointers. I got some questions that I
like to post to the experts here, hope you can help to clarify my
doubts. I'm using g++ version 3.3.4. I created 3 classes as below for
testing some concepts. The questions are written as comments in
Bclass.h file. Thank you for your time and tips!

------------runtime errors------------
{8=> main
Aclass created.
Bclass instantiated.
main: Aclass.h:19: void Aclass::test(): Assertion `b' failed.
Aborted
-------------file: main.cc------------
#include "Aclass.h"

int main(){
Aclass a;
a.test();
}

-------------file: Aclass.h-----------
#ifndef ACLASS_H
#define ACLASS_H

#include "Bclass.h"
#include <stack>
#include <cassert>

class Aclass{
public:
Aclass(){
std::cout << "Aclass created." << std::endl;
}
~Aclass(){ std::cout << "Aclass destructed." << std::endl; }

void test(){
Bclass *b=NULL;
if( box.empty() ){
create(b);
assert(b); // As expected this fails during runtime
/* Qn: Is the failure because pointer 'b' is pointing to NULL?
* Qn: Is the reason why the call to "create" function without effect
* because the local pointer 'ptr' was changed to point to a temporary object?
*/
}
delete b;
}

protected:
void create(Bclass *ptr){
box.push( new Bclass() );
ptr = box.top();
box.pop();// memory is pop
assert(ptr); // this is fine
/* Qn: Is the reason the assertion pass because local pointer 'b' is
* still referencing the memory?
* Qn: Is the memory release or considered unreferenced only if
* we get out of the "create" function?
*/
}

private:
std::stack<Bclass* > box;
};

#endif

-------------file: Bclass.h-----------
#ifndef BCLASS_H
#define BCLASS_H
#include <iostream>

class Bclass{
public:
Bclass(){ std::cout << "Bclass instantiated." << std::endl; }
~Bclass(){ std::cout << "Bclass destroyed." << std::endl; }
};
#endif

That problem is that yuo're passing the pointer by value.
If you want to modify the calling functions argument, you have to
either pass the pointer by reference, or pass a pointer to a pointer.
Example:
//Ref
void create(Bclass *& ptr){
box.push( new Bclass() );
ptr = box.top();
box.pop();// memory is pop
assert(ptr); // this is fine

Or *********************
//Pointer to a pointer method
void create(Bclass ** ptr){
box.push( new Bclass() );
(*ptr) = box.top();
box.pop();// memory is pop
assert((*ptr)); // this is fine

Another option, which is the one I recommend, is to return the pointer.
Bclass *create(void){
Bclass * ptr = NULL;
box.push( new Bclass() );
ptr = box.top();
box.pop();// memory is pop
assert(ptr); // this is fine
return ptr;

Jul 23 '05 #4
PKH

"DamonChong" <so********@excite.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Hi,

I am still struggling to master C++ and is trying to understand how to
achieve passing arguments using pointers. I got some questions that I
like to post to the experts here, hope you can help to clarify my
doubts. I'm using g++ version 3.3.4. I created 3 classes as below for
testing some concepts. The questions are written as comments in
Bclass.h file. Thank you for your time and tips!

------------runtime errors------------
{8=> main
Aclass created.
Bclass instantiated.
main: Aclass.h:19: void Aclass::test(): Assertion `b' failed.
Aborted
-------------file: main.cc------------
#include "Aclass.h"

int main(){
Aclass a;
a.test();
}

-------------file: Aclass.h-----------
#ifndef ACLASS_H
#define ACLASS_H

#include "Bclass.h"
#include <stack>
#include <cassert>

class Aclass{
public:
Aclass(){
std::cout << "Aclass created." << std::endl;
}
~Aclass(){ std::cout << "Aclass destructed." << std::endl; }

void test(){
Bclass *b=NULL;
if( box.empty() ){
create(b);
assert(b); // As expected this fails during runtime
/* Qn: Is the failure because pointer 'b' is pointing to NULL?
* Qn: Is the reason why the call to "create" function without effect
* because the local pointer 'ptr' was changed to point to a temporary
object?
*/
}
delete b;
}

Is should fail because b is NULL. When you call create(b), you're just
passing the address (NULL in this case) of whatever b is pointing at as a
parameter, and not b itself. It might help to think of regular variables are
just 'names' for memory-locations where the variables value are stored.
Pointers to variables are the same, only that they use their
memory-locations to store the address of another variables memory-location.

If you want b to point to the object created in 'create', you could return
the address of the new object like this:

Bclass* create(){ return new Bclass();}

or use a pointer to a Bclass pointer like this:

void create(Bclass** pptr){Bclass* ptr = new Bclass(); *pptr = ptr;} //
stores the address of the new object in b's memory location when called like
this 'create(&b);'


protected:
void create(Bclass *ptr){
box.push( new Bclass() );
ptr = box.top();
box.pop();// memory is pop
assert(ptr); // this is fine
/* Qn: Is the reason the assertion pass because local pointer 'b' is
* still referencing the memory?
* Qn: Is the memory release or considered unreferenced only if
* we get out of the "create" function?
*/
}


b has no meaning inside this function. All you know is that you got a
parameter called ptr which contains the memory address of a Bclass object.
The assertion passes because ptr is pointing at the new object. Memory
allocated with 'new' is not released automatically when you leave a
function.

PKH


Jul 23 '05 #5
Thanks alot! That clarifies much!

Jul 23 '05 #6

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

Similar topics

41
by: Berk Birand | last post by:
Hi, I am just learning about the array/pointer duality in C/C++. I couldn't help wondering, is there a way to pass an array by value? It seems like the only way to do is to pass it by...
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...
3
by: Roubles | last post by:
Hi All, Here's my problem, I have a bunch of code that passes an allocated object (say obj) to a function, and then dereferences that allocated object when the function returns: foo(obj);...
83
by: Anonymous | last post by:
Came across some code summarized as follows: char const* MyClass::errToText(int err) const { switch (err) { case 0: return "No error"; case 1: return "Not enough"; case 2: return "Too...
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...
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...
15
by: ramif | last post by:
Does call by reference principle apply to pointers?? Is there a way to pass pointers (by reference) to functions? Here is my code: #include <stdio.h> #include <stdlib.h>
12
by: Bryan Parkoff | last post by:
I write my large project in C++ source code. My C++ source code contains approximate four thousand small functions. Most of them are inline. I define variables and functions in the global scope....
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.