Question

The function is this:

Set::Set(Multinumber* tempArray[], int tempSize)
{
 numElements = tempSize;
 capacity = tempSize*2;
 setArray = new Multinumber*[capacity];
 for (int i=0; i<numElements; i++)
 {
  addElement(tempArray[i]);
 }
}

The variable setArray is declared in my header to be of type Multinumber**

It segfaults whenever I call it with this:

Multinumber* carr[2];
carr[0]=c4;
carr[1]=c5;
Set setb(carr,2);

c4 and c5 are already declared pointers to objects of the proper type.

Any help would be much appreciated.

EDIT: Code below is addElement function (apologies for the indentation)

const Set Set::operator+(const Set& rhs) const
{
 Set result;
 int i=0, j=0;

 while ((i < numElements) && (j < rhs.numElements))
 {
  Multinumber* toadd=new Multinumber;
  toadd=*(setArray[i]) + *(rhs.setArray[j]);
  result.addElement(toadd);
  i++;
  j++;
 }

 while ((i < numElements))
 {
  result.addElement(setArray[i]);
  i++;
 } 


 while ((j < rhs.numElements))
 {
 result.addElement(rhs.setArray[j]);
 j++;
 }


 return result;
}

EDIT: Based on numerous cout statements, error seems to be in this function:

 bool Set::isFull()
 {
  return (numElements == capacity);
 }

EDIT: Changed array indices, but still segfaults

Was it helpful?

Solution

carr[1]=c4;
carr[2]=c5;

Shouldn't that be

carr[0]=c4;
carr[1]=c5;

?

Piece of advice: If you load this up in a debugger, such as gdb, it would have identified the culprit line and you would've seen your error very quickly.

OTHER TIPS

Arrays use zero-based indexes, so setting carr[2] to anything in a two-length array is undefined behavior. You should be grateful it was a segfault. :-)

Try:

Multinumber* carr[2];
carr[0]=c4;
carr[1]=c5;
Set setb(carr,2);

That should take care of the segfault.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top