C++中如何调整对象动态数组大小?现有代码出现段错误求助
Hey there! Let's break down what's going wrong with your code and fix that segmentation fault step by step.
1. First, a Small Fix in Your Constructor
In your constructor, you initialize temp1 with new house[num_houses] when num_houses is 0. While new T[0] is technically allowed in C++, the returned pointer can't be dereferenced (you can't access temp1[0] with it), and it's an unnecessary source of confusion. A safer approach is to initialize temp1 to nullptr instead:
player(){ num_houses = 0; temp1 = nullptr; // No need to allocate a 0-size array }
2. The Core Issue: Redundant Logic in add_house
Your add_house function does unnecessary double memory allocation/copying, which not only wastes efficiency but also increases the chance of bugs. Worse, if your house class has pointer members or requires deep copying, the default shallow copy behavior will cause multiple objects to share the same memory—leading to double-free errors and segmentation faults when you delete arrays.
Let's rewrite add_house to simplify the logic and eliminate redundant steps:
void player::add_house(house tkn){ // Create a new array that's one element larger than the current house* new_temp = new house[num_houses + 1]; // Copy all existing houses to the new array for(int i = 0; i < num_houses; i++){ new_temp[i] = temp1[i]; } // Add the new house to the end of the new array new_temp[num_houses] = tkn; // Clean up the old array delete[] temp1; // Update our pointer and house count temp1 = new_temp; num_houses++; }
This version cuts out the extra temp array, making the flow clearer and reducing opportunities for mistakes.
3. Critical Check: Does house Have Proper Copy Semantics?
If your house class manages dynamic resources (like pointers to heap memory, file handles, etc.), you must implement a copy constructor and copy assignment operator (following the Rule of Three). The default shallow copy will just copy pointer values, not the data they point to—so when you delete an array, all copied house objects will end up pointing to freed memory, causing segmentation faults.
For example, if your house class looks like this:
class house{ private: char* address; public: house(const char* addr){ address = new char[strlen(addr) + 1]; strcpy(address, addr); } // No copy constructor/assignment or destructor };
You need to add deep copy logic:
// Copy constructor house(const house& other){ address = new char[strlen(other.address) + 1]; strcpy(address, other.address); } // Copy assignment operator house& operator=(const house& other){ if(this != &other){ // Prevent self-assignment delete[] address; // Free current resource address = new char[strlen(other.address) + 1]; strcpy(address, other.address); } return *this; } // Destructor to clean up resources ~house(){ delete[] address; }
4. Pro Tip: Use std::vector to Avoid Manual Memory Headaches
As a student, learning manual memory management is important, but for real-world code (and to avoid these kinds of bugs entirely), use the C++ standard library's std::vector. It handles all memory allocation, copying, and cleanup automatically.
Here's how to refactor your player class with vector:
#include <vector> class player{ private: std::vector<house> houses; // Replace raw array with vector public: player() = default; // Vector initializes empty automatically void add_house(house tkn){ houses.push_back(tkn); // One line to add a house—no new/delete needed! } // Removing a house is just as easy, e.g., remove the last one: void remove_last_house(){ if(!houses.empty()){ houses.pop_back(); } } };
This eliminates all manual memory management and the risk of segmentation faults from incorrect pointer handling.
内容的提问来源于stack exchange,提问作者Rob

