Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 314
  • Last Modified:

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

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
tvkalyan
Asked:
tvkalyan
  • 3
  • 3
  • 2
  • +2
1 Solution
 
AxterCommented:
Please show your code.
0
 
KocilCommented:
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
 
madfaceCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
tvkalyanAuthor Commented:
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
 
AxterCommented:
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
 
tvkalyanAuthor Commented:
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
 
KocilCommented:
>  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
 
KocilCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
tvkalyanAuthor Commented:
Thanx a lot,that was great.That really was awesome.Thanx once again.
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 3
  • 3
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now