使用 memcpy 将动态数组的内容复制到另一个会产生运行时错误

Using memcpy to copy the content of a dynamic array onto another produces a runtime error

所以我试图创建一个具有动态大小的堆栈,这意味着堆栈的容量将根据需要动态变化。这个概念在我的脑海中完美地实现了,创建一个函数名称 memoryManagement(int i),它通过一个名为 usedCapacity 的变量获取当前存储在堆栈中的数据的大小。在此之后,程序应该创建一个新数组,使用 memcpy 将旧数组的内容复制到新数组中。最后,将新数组的内容复制回具有新容量的旧数组。但是,当我 运行 我的程序时,我总是收到 运行 时间错误。此外,根据我调用 showStack 函数的位置,我有时会得到颠簸数字而不是我压入堆栈的实际值。如果有人能指出我做错了什么,我将不胜感激。

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>

using namespace std;

class Stack
{
public:
    //stack functions
    Stack();
    void push(int a);
    int pop();
    int peek() const;
    void showStack();
    ~Stack();
    //memory management
    void memoryManagement(int a);
    //void setCapacity(int  );
    //void ensureCapacity(int minCapacity);
private:
    int top;
    int * arr;
    int capacity;
    int usedCapacity;
};

//////////////////////////////////////////////////////////////////////////////////

int main() {

    Stack calc;
    calc.push(11);
    calc.push(33);
    calc.showStack();
    calc.push(23);
    calc.push(43);

    return 0;
}

//////////////////////////////////////////////////////////////////////////////////

Stack::Stack()
{
    top = -1;
    usedCapacity = 0;
    capacity = 1;
    arr = new int[capacity];
}

void Stack::push(int a)
{
    if (top > capacity)
        throw "Stack overflow";
    top++;
    usedCapacity++;
    arr[top] = a;
    memoryManagement(usedCapacity);
}

int Stack::pop()
{
    if (top <= -1)
        throw "Stack underflow";
        arr[--top];
}

int Stack::peek() const
{
    return top;
}

void Stack::showStack()
{
    for (int i = 0; i < capacity; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
}

Stack::~Stack()
{
    delete[] arr;
}

void Stack::memoryManagement(int a)
{
    if (a >= capacity)
    {
        int newCapacity;
        newCapacity = (a * 3) / 2 + 1;

        int * arr2 = new int[newCapacity];
        memcpy(arr2, arr, sizeof(int) * usedCapacity);

        delete[] arr;
        arr = arr2;
        delete[] arr2;
    }
}

为什么要从 memoryManagement 中删除 arr2?你不应该,因为这显然是你的新 class 属性(你做了 arr = arr2):

但这还不够(然后您的程序将开始在 push 上抛出异常...因为您还忘记修改 capacity 属性。这是您的工作 memoryManagement功能:

void Stack::memoryManagement(int a)
{
    if (a >= capacity)
    {
        int newCapacity;
        newCapacity = (a * 3) / 2 + 1;

        int * arr2 = new int[newCapacity];
        memcpy(arr2, arr, sizeof(int) * usedCapacity);

        delete[] arr;
        arr = arr2;
        capacity = newCapacity; // Don't forget that!
        //delete[] arr2;        // Don't do that!
    }
}