0

While compiling my code I came across a segmentation fault in my code and really don't understand them. I'm not looking for a answer to my code more something that would help me understand what a segmentation fault is, and why it happens. For reference though, here is the code I was working on (I know its not a good way of going about this, but I am still learning).

void PhoneBook::verifyAllContacts() {
    Contact* listOfNumbers;
    listOfNumbers = new Contact[numContacts];
    int tempHoldCount = 0;

    for(int i = 0; i < numContacts; i++) {
        if(listOfNumbers[i].verifyPhoneNumber() == true && listOfNumbers[i].getEmergencyContact()->verifyPhoneNumber() == true)
            tempHoldCount++;
    }

    Contact* validContactList;
    validContactList = new Contact[tempHoldCount];

    for(int z = 0; z < tempHoldCount; z++) {
        for(int s = 0; s < numContacts; s++) {
            if(listOfNumbers[s].verifyPhoneNumber() == true && listOfNumbers[s].getEmergencyContact()->verifyPhoneNumber() == true)
                validContactList[z] = listOfNumbers[s];
        }
    }

    delete listOfNumbers;
}
Suraj Jain
  • 4,463
  • 28
  • 39
grillo
  • 346
  • 1
  • 2
  • 13
  • What are you trying to do? The line `validContactList[z] = listOfNumbers[s];` seems to do nothing useful since `validContactList` is a function-scoped symbol; i.e. it will be destroyed when the function returns, leaving you with a memory leak containing all those contacts you created with `validContactList = new Contact[tempHoldCount];` – Eric Jun 17 '15 at 18:11

2 Answers2

0

A segmentation fault generally occurs when your code accesses memory outside of what memory is assigned to the variable being used. I.E.

int myarray[10];

for(int i=0;i<=10;i++)
{
  myarray[10] = 0;
}

will create a segmentation fault on runtime because myarray[10] is not a declared variable since myarray only has 10 iterations (0-9) not 11

timtoy1
  • 31
  • 5
0

Since you used new [] to allocate memory for lisOfNumbers, you need to use

delete [] listOfNumbers;

That may not fix your segmentation fault problem but it's the right thing to do. Strictly speaking, using

delete listOfNumbers;

is cause for undefined behavior.

R Sahu
  • 204,454
  • 14
  • 159
  • 270