我正在编写一个程序,它从用户那里获取一些联系信息,并在数组变满时动态地增加数组。但是,当我尝试运行该程序时,我从“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 ¤tLength, 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 ¤tLength, Contact *&contacts)
好的方法是停止这种手动分配的无意义的内存并使用 std::vector<Contact>
!
关于c++ - 尝试重新分配内存时出现写访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54903664/