473,725 Members | 2,070 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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<Bcla ss* > 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 1933

"DamonChong " <so********@exc ite.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.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*****@hotmai l.com> wrote in message
news:xg******** ************@bg tnsc05-news.ops.worldn et.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<Bcla ss* > 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********@exc ite.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.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
8327
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 reference?? Thanks, BB
110
9936
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 must be an object instead of
3
1383
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); obj->foobar = TRUE; The issue is that foo *might* free obj. So the dereference can be
83
3947
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 much"; default: return "Unknown error";
14
20405
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 passed also. I understand that this way of passing the array is by value and if the prototype is declared as foo(int *), it is by reference in which case the value if modified in the function will get reflected in the main function as well. I dont...
10
13660
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 function is also modified. Sometimes I wish to work with "copies", in that when I pass in an integer variable into a function, I want the function to be modifying a COPY, not the reference. Is this possible?
6
2713
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 pass by reference in C since you are just passing an address (or a pointer value address I guess?). So I was wondering is this correct?
15
2020
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
3014
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. The global variables and global functions are hidden to prevent from accessing by the programmers. All global functions share global variables. Only very few global functions are allowed to be reusability for the programmers to use. Few...
0
9401
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
9257
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...
1
9176
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9113
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
8097
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
6702
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
4519
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...
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
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.