c++ - 为什么我在 C++ 中收到指针数组的 "pointer being freed was not allocated"错误?

标签 c++ arrays pointers dynamic

我正在使用一个动态指针数组。该项目需要此设置。当我执行时,我收到一个错误,指出未分配正在释放的指针。

已更新以添加动态代码。当我尝试访问数组时,函数会抛出错误的访问错误,并且会因删除动态数组而出现段错误。

class Person
{
private:
string firstName;
string lastName;
int age;
int telNum;
int numAddrs;
//Address* addrs[10];
Address* addrs;

public:
Person(string, string, int, int);
Person();
Person(const Person &p);

~Person();

void setFirstName(string);
void setLastName(string);
void setAge(int);
void setTelNum(int);
void setAddress(Address*);
void setNumAddrs(int);

string getFirstName();
string getLastName();
int getAge();
int getTelNum();
Address* getAddress();
int getNumAddrs();

void displayPerson();
void addAddress(Address &newAddr);

Person& operator =(const Person &RHS);


};

Person::Person()                                //default
{
firstName = "John";
lastName = "Doe";
age = -1;
telNum = -1;

numAddrs = 0;               //current number of addresses for this person

addrs = new Address*[10](); //throws error, won't compile
//new dynamic array of pointers, initialize to NULL

}

Person::Person(string first, string last, int y, int t)
{                                               //constructor to  initialize              Person
firstName = first;
lastName = last;
age = y;
telNum = t;

numAddrs = 0;                   //current number of addresses for this     person

addrs = new Address*[10](); throws error, won't compile
//new dynamic array of pointers, initialize to NULL

}


Person::Person(const Person &p)     //copy constructor
{
this->firstName = p.firstName;
this->lastName = p.lastName;
this->age = p.age;
this->telNum = p.telNum;
this->numAddrs = p.numAddrs;


delete [] addrs;        //delete previous dynamically allocated memory

addrs = new Address*[10](); //throws error, won't compile
//new dynamic array of pointers,     initialize to NULL

for (int i = 0; i<10; i++)    //copy addresses to new object
{
this->addrs[i] = p.addrs[i];
}

}

最佳答案

addrs 不是一个指针,它是一个数组。你不需要用 new 为它分配空间,因为它的内存是作为类对象的一部分分配的。它是一个指针数组,所以你需要在构造函数中为每个元素分配内存:

for (int i = 0; i < 10; i++) {
    addrs[i] = new Address;
}

然后在析构函数中,您需要删除每个地址。​​

for (int i = 0; i < 10; i++) {
    delete addrs[i];
}

但是,有一个问题。您的赋值运算符将所有 addrs[i] 从 src 复制到目标。所以现在您有两个 Person 对象,它们的指针指向相同的 Address 对象。如果它们中的任何一个被破坏,它将释放所有 Address 对象,然后另一个 Person 将在其 addrs 数组中具有无效指针。

不清楚为什么您需要一个指针数组而不是一个 Address 对象数组:

Address addrs[10];

那么你就不需要使用new或者delete了。

此外,在现代 C++ 中,通常认为使用 std::vector 等容器更好。您还可以使用智能指针类来处理多个容器之间共享同一指针的问题。

关于c++ - 为什么我在 C++ 中收到指针数组的 "pointer being freed was not allocated"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38153960/

相关文章:

c++ - img.at<uchar>(i,j) 是什么意思?

python - Numpy:沿指定轴 reshape 数组

ruby-on-rails - 在 Postgres 中使用整数数组初始化模型

javascript - 将变量与自身进行比较

c++ - 指针声明

阐明 C 中的结构指针数组

c++ - 在 boost::ptr_unordered_map 中存储指向 const 对象的指针

c++ - 设计问题——静态变量继承

c++ - 我如何定义一个将任何类型的指针值作为参数的函数?

c++ - 定义结构时是否可以强制字符串为特定大小?