user1084680
user1084680

Reputation: 11

Program Crashes when I try to compare two strings in c++?

int removeContact(Contact *newPtr, int runningTotal)
{
    //define variables
    string remove;
    int next;

    //prompt user for name they wish to remove
    cout << "Enter the name you would like to delete (Last name first): ";
    cin.ignore();
    getline(cin, remove);

    for (int t=0; t<=runningTotal; t++)
    {   
        if (remove.compare(newPtr[t].name) == 0)  
        {

            //calls function moveArrayElements function
            moveArrayElements(newPtr, runningTotal, t);

            //decrement runningTotal
            runningTotal--;

            //prompt user contact was found
            cout << "Contact was found and deleted!";

            next=1;
        }   

}

if(next!=1)
{
   cout<< "ERROR: Contact was not found!"; 
}

return runningTotal;
}

This function is apart of a larger c++ program that is designed to manage a persons contact information. This function is suppose to remove a contact.

The problem I'm have is with the if (remove.compare(newPtr[t].name) == 0) statement. When my program gets to this part of the code it will crash without giving any errors. I tried straight up comparing both the stings with == operator, but this still results in a crash of my program...

Also, what make this so strange is that this code works perfectly when the function is called while my program is running with the contact that I'm trying to remove not stored in a text file.

However, when I close my program, and load my contact information from the text file, my program will crash... I know that my program is reading the file into the proper string array because I have a print function, so I know that all of my contacts are being transferred into the proper structure arrays...

Any ideas on how I can fix this? Any help would be appreciated! Thanks

UPDATE: I took the suggestions in the comments and changed my for loop to

t<runningTotal;

However, when I do this my program doesn't crash, but it wont's compare the strings...

Upvotes: 1

Views: 1297

Answers (2)

engf-010
engf-010

Reputation: 3929

i guess the for statement should be:

for (int t=0; t<runningTotal; t++) 

Upvotes: 1

AusCBloke
AusCBloke

Reputation: 18492

If runningTotal is the size of your array, then the range of valid elements is [0, runningTotal). In the below code, you're looping up to runningTotal inclusive, when there isn't a valid Contact object there:

for (int t=0; t<=runningTotal; t++)
{   
    if (remove.compare(newPtr[t].name) == 0)

Therefore when you go and dereference newPtr[t], for t = runningTotal and then try and get the name element, you'll be causing undefined behaviour and may cause a crash.

Try changing t<=runningTotal to t < runningTotal to see if the problem goes away.

Also, is there a reason why you're using arrays as opposed to an std::vector?

Upvotes: 2

Related Questions