0

I am pulling names as strings from a file, create a Person *p object, and put it into an array. Then to search the array for a name but when I try to fetch the name I get a segmentation fault.

Why is this segmentation fault happening, and what can I do to fix it?

#include <iostream>
#include <string>

using namespace std;

class Person {

private:
    string firstName;
    string lastName;
    string phoneNumber;

public:
    Person();
    Person(string f, string l, string n);
    ~Person(void);

    void setName()
    {
    }
    string getFirstName()
    {
        return firstName;
    }
    string getLastName()
    {
        return lastName;
    }

    string getNumber() { return phoneNumber; }

    void print();
};

Array creation.

{
            ifstream file;

            file.open("phonebook.txt");

            if (!file.is_open()) //Check for File Error.
            {
                cerr << "Failed to open file" << endl;
                exit(1);
            }

            //Get Array Size
            string line;
            while (getline(file, line))
            {
                count++;
            }
            file.close();

            //Create an array
            Person *arrList[count];
            buildArray(arrList, count);

        if (uInput == "a" || uInput == "A") //To add
        {
            int x = addPerson();
            if (x == 1)
            {
                count++;
            }
            delete[] arrList;
        }


void buildArray(Person *arr[], int size)
{
    string f, l, n;
    ifstream file;
    file.open("phonebook.txt");
    for (int i = 0; i < size; i++)
    {
        file >> f >> l >> n;
        Person *p = new Person(f, l, n);
        arr[i] = p;
        delete p;
    }
}

The search, This is the part that has the trouble. I have tried a few different things including creating 2 Persons, and comparing their parts but whenever it goes into the .h it can not return the name.

if (uInput == "s" || uInput == "S")
            {                   //To Search
                string f, l;

                cout << "Find Who (Firstname Lastname) " << endl;
                cin >> f >> l;
                Person *n = new Person(f, l, "");
                int i = 0;
                bool found = false;

                while (i <= count && found == false)
                {
                    Person *p = new Person("", "", "");
                    p = arrList[i];

                    if (p->getFirstName() == n->getFirstName() && p->getLastName() == n->getLastName())
                    {
                        arrList[i]->print();
                        found = true;
                        delete p;
                        delete n;
                    }
                    i++;
                }
                while (i == count && found == false)
                {
                    cout << "No results found. " << endl;
                    found = true;
                }
            }
AStopher
  • 4,207
  • 11
  • 50
  • 75
  • 2
    Please edit your question to add your code, and what attempts you've made to solve the problem. Once you've added that, I'll vote to re-open. – AStopher Oct 10 '20 at 21:21
  • It wont let me add the code, even when I indent – James Stark Oct 10 '20 at 21:36
  • Type ``` press enter paste your 10 to 50 lines of code type ``` press enter again – drescherjm Oct 10 '20 at 21:37
  • All questions here should have all relevant information ***in the question itself as plain text***. Links can stop working at any time making questions meaningless. Code, data, or errors, shown as images cannot be copy/pasted; or edited or compiled for further research and investigation. Please [edit] this question. All code must meet all requirements of a [mre]. You can find many other questions here that explain everything in plain text, please use them as an example for how your question should look. – Sam Varshavchik Oct 10 '20 at 21:37
  • _"I can't share images."_ That's intentional. _"Or paste code..."_ [You can](https://stackoverflow.com/editing-help#code), please do so. I'd also recommend you take the [tour], and inform yourself what and how you can ask here at the [help]. – πάντα ῥεῖ Oct 10 '20 at 21:37
  • 1
    Really? Mostly image-dumps are now blocked? Best news I've heard in a while. A long overdue change. – Sam Varshavchik Oct 10 '20 at 21:39
  • 1
    @JamesStark If unsure how to format your code properly, paste it as text and we'll edit it to format it properly for you. – AStopher Oct 10 '20 at 21:39
  • 1
    @Sam Under 10 rep, that always was the case. – πάντα ῥεῖ Oct 10 '20 at 21:43
  • @πάνταῥεῖ With all due respect, we need to help new users learn how to use the site. If it means formatting a question properly so the user can see how to properly construct their question going forward, so be it. These are new users, we should be educating them. – AStopher Oct 10 '20 at 21:45
  • @JamesStark Your `Person` class looks fine so far. I'd guess you screwed something with the arrays you mention. – πάντα ῥεῖ Oct 10 '20 at 21:45
  • @JamesStark The code you posted looks fine to me but doesn't show us how you're calling it, please add that code if possible. – AStopher Oct 10 '20 at 21:48
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/222836/discussion-between-astopher-and--). – AStopher Oct 10 '20 at 21:52
  • 2
    Okay, thanks @πάνταῥεῖ for the tour advice I will do that, Astopher okay I figured out how to format it thank you. – James Stark Oct 10 '20 at 21:54
  • @Astopher Can't Use chat till I have 20 rep – James Stark Oct 10 '20 at 21:56
  • `arr[i] = p; delete p;`, so you save the pointer to the object in the array. And then you delete the object. The pointer in the array now points to a destroyed object, and attempting to dereference it is undefined behavior, and the reason for your crash. And the array itself is also a non-standard C++ variable-length array. There are multiple other fundamental issues with the shown code. – Sam Varshavchik Oct 10 '20 at 22:02
  • @JamesStark Apologies, I completely forgot about that. I've voted to re-open your question as it now has sufficient info. The one thing that stands out to me are your `delete`s- you `delete` pointers and then try to use them, which means that the variable points to the former memory location but nothing is there/something else is there, hence the segfault. The modern way of using pointers is via smart pointers, you may wish to look into them as that way you don't need to worry too much about destroying the pointer (they automatically destroy themselves when no longer needed). – AStopher Oct 10 '20 at 22:02
  • Make the [mre]. The main reason we ask for them is it's a powerful debugging technique. More often than not, you get part way into making the MRE and the reduced noise around the bug allows you to see and solve it yourself. If you still can't see the bug (or can and don't know how to solve it) the odds of one of us having a solution goes way up. – user4581301 Oct 10 '20 at 22:03
  • @AStopher Oh okay I understand, so I shouldn't delete them at that point. When should I delete them? – James Stark Oct 10 '20 at 22:05
  • @JamesStark You should delete only when you no longer need them, at the end of your code (when they're no longer needed). Alternatively if you use `std::shared_ptr`, you don't need to `delete` because it'll automatically delete itself when the variable is no longer used. – AStopher Oct 10 '20 at 22:08
  • @SamVarshavchik Ok. Are those fundamental issues something I'm likely to learn in the future, or should I understand them already? I am 3 weeks in to C++ class and this is my first assignment. – James Stark Oct 10 '20 at 22:08
  • 4
    I would think that before doing any work related to dynamic memory allocation, sufficient time gets spent explaining how C++ works in this respect, on the fundamental basis. And before that, sufficient gets spent explaining C++'s memory model: what pointers are, how they work, etc... – Sam Varshavchik Oct 10 '20 at 22:10
  • @SamVarshavchik Okay, thanks. Yeah I have only had a few lectures on it so far. – James Stark Oct 10 '20 at 22:14
  • 1
    @AStopher Thank You! It does what its supposed to now! – James Stark Oct 10 '20 at 22:17
  • @JamesStark No problem, if your question is re-opened I'll add an answer :-). – AStopher Oct 10 '20 at 22:22

0 Answers0