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

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

本文关键字:动态 数组 另一个 运行时错误 memcpy 使用 复制      更新时间:2023-10-16

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

#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?你不应该,因为这显然是你的新类属性(你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!
    }
}