c++ - 尝试重新分配内存时出现写访问冲突

标签 c++ visual-studio pointers

我正在编写一个程序,它从用户那里获取一些联系信息,并在数组变满时动态地增加数组。但是,当我尝试运行该程序时,我从“iosfwd 标准 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 函数中。但我不知道我哪里搞砸了。请帮忙。

最佳答案

growArray(currentLength, contacts);

指针的拷贝 contacts在函数内部修改;但在外面,指针的值保持不变。在growArray之后返回,contacts指向已删除的内存,因此是 UB,因此是崩溃。

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

基本上有两种解决方案:坏的和好的。不好的是改了growArray的签名引用指针:

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

好的方法是停止这种手动分配的无意义的内存并使用 std::vector<Contact> !

关于c++ - 尝试重新分配内存时出现写访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54903664/

相关文章:

c++ - 你如何使用CUFFT的批处理模式?

c# - 自动重构为 string.Format

android - Xamarin - 当我将我的应用程序发布到谷歌商店时,我应该使用什么 apk 包

c++ - 比较双向链表中的指针?

c - 如何以可移植的方式从指向结构成员的指针计算指向结构开头的指针?

c++ - 字符串流数据损坏的问题。

c++ - 编译器内联什么调用?

c++ - 从 ifstream 读取不会读取空格

visual-studio - 在 Visual Studio 调试器中查看命名空间全局变量?

c - 使用++增加数组指针