realloc():无效的旧大小,即使使用 malloc() 分配内存

realloc(): invalid old size even when malloc() is used to allocate memory

我正在尝试用 C++ 实现动态堆栈。 我在 class 堆栈中有 3 个成员 1.cap 是容量。 2.top- 指向栈顶 3. arr- 指向整数的指针。

在 class 构造函数中,我将内存分配给堆栈 (malloc)。 稍后在 meminc() 中我试图重新分配内存。

我已经编写了一个函数 meminc() 来重新分配内存,但是我得到了这个无效的旧大小错误。

如果您让我知道此代码中的错误,将会很有帮助。我也会感谢给我的任何建议。 谢谢。

#include <iostream>

using namespace std;

#define MAXSIZE 5

class stack {
    int cap;
    int top;
    int *arr;

public:
    stack();
    bool push(int x);
    bool full();
    bool pop();
    bool empty();
    bool meminc();
};

stack::stack()
{
    cap = MAXSIZE;
    arr = (int *)malloc(sizeof(int)*MAXSIZE);
    top = -1;
}

bool stack::meminc()
{
    cap = 2 * cap;
    cout << cap << endl;
    this->arr = (int *)realloc(arr, sizeof(int)*cap);
    return(arr ? true : false);
}

bool stack::push(int x)
{
    if (full())
    {
        bool x = meminc();
        if (x)
            cout << "Memory increased" << endl;
        else
            return false;
    }

    arr[top++] = x;
    return true;
}

bool stack::full()
{
    return(top == MAXSIZE - 1 ? true : false);
}

bool stack::pop()
{
    if (empty())
        return false;
    else
    {
        top--;
        return true;
    }
}

bool stack::empty()
{
    return(top == -1 ? true : false);
}

int main()
{
    stack s;
    char y = 'y';
    int choice, x;
    bool check;

    while (y == 'y' || y == 'Y')
    {
        cout << "                 1.push\n                    2.pop\n" << endl;
        cin >> choice;

        switch (choice)
        {
        case 1: cout << "Enter data?" << endl;
            cin >> x;
            check = s.push(x);
            cout << (check ? "              push complete\n" : "              push failed\n");
            break;

        case 2: check = s.pop();
            cout << (check ? "              pop complete\n" : "               pop failed\n");
            break;

        default: cout << "ERROR";
        }
    }
}

full函数不正确。应该是

bool stack::full()
{
    return(top == cap - 1 ? true : false);
}

或更简单并添加 const

bool stack::full() const
{
    return top == cap - 1;
}

您还错误地使用了 top 变量。由于 top 从 -1 开始,您应该在设置值之前递增 top,而不是之后递增

arr[++top] = x;

不是bug,但从设计的角度meminc应该是一个私有函数。

添加到约翰的回答中,

您使用 realloc() 的方式...有缺陷。

bool stack::meminc()
{
    cap = 2 * cap;
    cout << cap << endl;
    this->arr = (int *)realloc(arr, sizeof(int)*cap);
    return(arr ? true : false);
}

如果 realloc() 失败,它将 return nullptr 并且指向原始内存区域的唯一指针 (arr) 将消失。另外,您应该简单地使用 return arr != nullptr;.

而不是 return(arr ? true : false);

正确的tm使用方法realloc():

bool stack::meminc()
{
    int *temp = (int*) realloc(arr, sizeof(*temp) * cap * 2);
    if(!temp)
        return false;
    cap *= 2;
    arr = temp;
    return true;
}

还有,你的copy-ctor、assignment operator和d-tor在哪里?