尝试重新分配内存时遇到写访问冲突

时间:2019-02-27 10:46:11

标签: c++ visual-studio pointers

我正在编写一个程序,该程序从用户那里获取一些联系信息,并在阵列装满后动态地增加阵列。但是,当我尝试运行该程序时,出现“写访问冲突”,并从“ iosfwd standard header”弹出一行。我不知道哪里出了问题。请帮忙。

我的代码如下:

# include "pch.h"
# include <iostream>
# include <string>

using namespace std;

struct Contact {
    string name;
    string number;
    string address;
    string exit;
};
void userPrompt(Contact &contact) {
    cout << "Name: ";
    getline(cin, contact.name);
    cout << "Phone number: ";
    getline(cin, contact.number);
    cout << "Address: ";
    getline(cin, contact.address);
    cout << "Exit? (y/n): ";
    getline(cin, contact.exit);
}
void printContact(Contact &contact) {
    cout << "Name: " << contact.name << endl;
    cout << "Phone number: " << contact.number << endl;
    cout << "Address: " << contact.address << "\n" << endl;
}
void growArray(int &currentLength, Contact *contacts) {
    int multiplyer = 2;
    Contact *new_array = new Contact[currentLength * multiplyer];
    for (int i = 0; i < currentLength; i++) {
        new_array[i] = contacts[i];
    }
    delete[] contacts;
    contacts = new_array;
    currentLength *= multiplyer;
}
void showAllContacts(Contact *contacts, int length) {
    for (int i = 0; i < length; i++) {
        if (contacts[i].name.length() != 0) {
            printContact(contacts[i]);
        }
    }
}
int main() {

    // Prompt the user to fill in the address book.
    // If the array gets full, make it bigger.

    Contact *contacts = new Contact[1];
    int currentLength = 1;
    int i = 0;
    while (true) {
        userPrompt(contacts[i]);
        if (contacts[i].exit == "y" or contacts[i].exit == "Y") {
            break;
        }
        i++;
        if (i == currentLength) {
            growArray(currentLength, contacts);
        }
    }

    // Show the address book

    showAllContacts(contacts, currentLength);
}

但是当我运行代码时,它会引发如下异常: enter image description here

“写访问冲突” 我认为错误是在growArray函数中。但是我无法排除我在哪里搞砸了。请帮忙。

1 个答案:

答案 0 :(得分:2)

growArray(currentLength, contacts);
指针contacts副本在函数内部进行了修改;但在外部,指针的值保持不变。 growArray返回后,contacts指向已删除的内存,因此指向UB,从而导致崩溃。

==> Full program demonstration of the issue <==

基本上有两种解决方案:不好的一种和好的一种。不好的办法是更改growArray的签名以引用指针:

void growArray(int &currentLength, Contact *&contacts)

一个好办法是停止这种无用的手动分配的内存,并使用std::vector<Contact>