?
Solved

Passing an Object which contains a pointer variable by value to a function

Posted on 2003-03-11
10
Medium Priority
?
312 Views
Last Modified: 2010-08-05
I am passing an object which contains a pointer variable by value to a function.It behaves properly inside the function but when i come out of the function (into main) and try operations on the object(declared in main) ,it gives me a segmentation fault.I want to know the reason why.There is no problem if i pass the object by reference or if i change the pointer variable to an array (and pass by value).
0
Comment
Question by:tvkalyan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +2
10 Comments
 
LVL 30

Expert Comment

by:Axter
ID: 8116505
Please show your code.
0
 
LVL 5

Expert Comment

by:Kocil
ID: 8117016
This func use pass by value

func(char* ptr)
{
   ptr = new char[10];
   strcpy(ptr, "ABC");
}

main()
{
   char *ptr1;
   func(ptr1);
   count << ptr1;
   delete[] ptr1;
}

It will be error because the ptr in func() is only a copy of the ptr1 in main(). So, although you change the ptr in the func(), the ptr1 in the main() won't be changed. When you return to the main, the ptr1 still contains uninitialized address -> segmentation fault.

If you use pass by reference
func(char* &ptr)
{
   ptr = malloc();
   strcpy(ptr, "ABC");
}

The ptr in func() is the ptr1 in main(). So when you malloc a memory for ptr, the ptr1 will be initialized. Then you can use it without error.
0
 
LVL 1

Expert Comment

by:madface
ID: 8118782
your making a copy of a pointer you want to use a reference of pointer.


func(char** ptr)
{
   *prt = new char[10];
    strcpy(*ptr, "ABC";
}

i had the same problem back when i was in school.
if you need more info just ask
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:tvkalyan
ID: 8122365
OK,Here's what i mean.An object contains a pointer variable which is used as a single dimension array.I am passing this object into the function by value.In the function ,I call some methods on the object which operate on the pointer variable.It works fine till here.But when i return back to main and then i call the same method(as before) which operates on the pointer variable,it gives me a segmentation fault.As you guys wrote in your comments i am not changing anything as far as the pointer variable goes,i am just accessing the variable and moreover i have no problems in my function ,it works very fine,the problem is when i come back to my main function.This leads to another question Should an object which contains a pointer variable as its member always be passed by reference only?
0
 
LVL 30

Expert Comment

by:Axter
ID: 8122440
Please show your code.

We can help you better if we can see exactly what you're doing.

Just copy and paste the sections of code that applies.
0
 

Author Comment

by:tvkalyan
ID: 8123931
OK ,Here's the function,the object is leftIm1:
THe function works fine

int calcvariance(int x,int y,int N,DIPImP5 leftIm1)
     {
          unsigned char newpix1,newpix2,newpix3;
          int sum1=0,sum2=0,min,i,j;
          for(int i=x;i<=(x+(N-1));i++)
          {
               for(int j=y;j<=(y+(N-1));j++)
               {
                    leftIm1.getPixel(i,j,newpix1);
                    leftIm1.getPixel(i-1,j,newpix2);
                    leftIm1.getPixel(i,j+1,newpix3);
                                        sum1=sum1+(newpix1-newpix2)*(newpix1-newpix2);
                    sum2=sum2+(newpix1-newpix3)*(newpix1-newpix3);
                                   }
          }
          min=calcmin(sum1,sum2);
          return min;
     }

Here's the main function:

/*MAIN*/
//DECLARATIONS AND INITIALIZATIONS

for(i=N/2;i<=N/2+(N-1);i++)
     {
          for(j=N/2;j<=N/2+(N-1);j++)
          {
/*PASSING THE OBJECT BY VALUE*/
               interest[index1]=calcvariance(i,j,N,leftIm);

//leftIm is an object of DIPImP5 here

/*     AFTER THIS IF I PERFORM AN OPERATION LIKE leftIm.getpixel,IT IS GIVING ME A SEG FAULT      */
               if (index1==N*N/2)
               {
                    interest[N*N]=i+N/2;
                    interest[N*N+1]=j+N/2;
               }
               index1=index1+1;
          }
     }


The header for DIPImP5 is :

class DIPImP5 {
 private:
  int rowCt, colCt, intenCt;
  unsigned char *pix;//Here pix is a pointer,if i change this to an array then there's no problem whatsoever
  void cleanUp();
  bool isValidIndex ( int r, int c );
  int getIndex ( int r, int c );
  bool getPixel ( int r, int c, unsigned char &newPix );
// getPixel operates on unsigned char *pix,i.e it just gets the values,it doesnt change anything in unsigned char *pix
     }
0
 
LVL 5

Expert Comment

by:Kocil
ID: 8124436
>  unsigned char *pix;//Here pix is a pointer,if i change this to an array then there's no problem whatsoever

Sure there will a problem if you not allocate memory for that pointer.
Make sure you do it in the constructor

DIPImP5::DIPImP5 {
  ...
  int array_size = ??? // compute this
  pix = new char[array_size];
  ...
}

Then you muse delete it in the destructor

DIPImP5::~DIPImP5 {
  ...
  delete pix;
  ...
}


0
 
LVL 5

Expert Comment

by:Kocil
ID: 8124465
Assume that you want a 2 dimensional array of rowCt * colCt, here is the tricks

// create col*row 1D array, but server as 2D array
//
DIPImP5::DIPImP5(int row, int col) {
 ...
 rowCt = row;
 colCt = col;
 pix = new char[col*row];
 ...
}

// delete it in the destructor
// notice the [], I forgot it before
DIPImP5::~DIPImP5 {
 ...
 delete [] pix;
 ...
}

// And use this for getPixel
bool getPixel ( int r, int c, unsigned char &newPix )
{
  if ((r < rowCt) && (c < colCt))
    newpix = pix[r * colCt + c];
  else
    newPix = 0; // put something here
}


0
 
LVL 30

Accepted Solution

by:
Mayank S earned 200 total points
ID: 8126464
The possible cause for an error would be that you have included a destructor function in your class DIPImP5, where you are deallocating the memory allocated to the pointer data-member.

When you will pass the object (in main ()), by value to another function, all the data-member values will get simply copied, including the value of the pointer data-member (or the location where it points to). So the pointer data-member of this object (local to the function) will also point to the same location as the pointer data-member of the object in main (). Now when this function finishes execution, the compiler will automatically call the destructor and it will deallocate the memory allocated for that object (and since you're having a delete statement there for the pointer, it'll deallocate the memory where the pointer pointed to). Now back in main (), your object's pointer data-member still points to the same location (which has now been deallocated), so it gives an error.

So the best way to solve it is to remove the destructor function from the class, or remove the delete statement from the destructor.

In case you're passing the object by address or by reference, remeber that no new object is being instantiated but the reference variable (or the pointer variable) is referring to (or pointing to) the same object which is there in main () (which has a lifetime as long as main () executes), and so the memory pointed ot by the pointer data-member is not being deallocated.

Hope that helps!

Mayank.
0
 

Author Comment

by:tvkalyan
ID: 8132768
Thanx a lot,that was great.That really was awesome.Thanx once again.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question