Hello, Joydeep

I have a couple of questions
first, what is the difference between
funct(int* &p) and funct(int *p)

isn't it the same, because we are passing down the pointer, then if the value of p is changed, it would be permanent, why bother putting the & in?

also, i have noticed that after executing the following code

int *val = new int;

delete val;

after deleting val, i can still output the value of val

how can i make sure that val has been deleted after executing delete val?


ANSWER: func( int * &p) takes a reference to a pointer.  func can change the contents of p (*p) or p itself (p=&j).

int j = 4, i = 2,*pi = &i;  func(i); allows func to change i to say 3, or pi to say &j.

func( int *p ) takes a pointer.  func can only change *p.


[an error occurred while processing this directive]---------- FOLLOW-UP ----------

thanks for the answer

but you still haven't answered my second question

let's say we have

int *val = new int;

delete val;

after deleting the val pointer, i can still output the value of val

how can i make sure that val has been deleted after executing delete val?


Sorry, I missed part 2...

You can still (but shouldn't) output or use val because it still contains the address that was deleted.  Delete effected the memory val pointed to (that memory will be potentially used on the next new) but not the pointer in val.

val is deleted in your program.  Good defensive programming practice is to set the pointer to NULL unless you delete it in a destructor.  I *always* use this:

if( var1 )
 delete var1;
var1 = NULL;

So that I never use or delete a deleted or NULL pointer.  If you do, the program will (should) trap because val = NULL; *val = 1; fails.  Note that x = *val; when val is NULL doesn't always trap (depends on OS and memory mapping being used).



All Answers

Answers by Expert:

Ask Experts


Bill A


I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.


I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

BS Computer Engineering

©2017 About.com. All rights reserved.

[an error occurred while processing this directive]