c++ - 重新分配(): invalid old size even when malloc() is used to allocate memory

标签 c++ memory dynamic malloc realloc

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

在类构造函数中,我将内存分配给堆栈 (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";
        }
    }
}

最佳答案

添加到约翰的回答中,

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

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

如果 realloc() 失败,它将返回 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;
}

此外,您的复制构造函数、赋值运算符和 d-tor 在哪里?

关于c++ - 重新分配(): invalid old size even when malloc() is used to allocate memory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54899968/

相关文章:

c++ - 实例化 C++ 类时内存中会发生什么

c++ - C++ 中的 "Static plugin"系统(通过构建系统)

c++ - 模板特化,其中参数是用于元编程的非类型参数化模板

c++ - 如何在可变参数包中找到 "min"类型?

c - C中的段错误(具有动态内存分配的二维数组)

javascript - 使用 JavaScript 创建带有对象数组的三级依赖下拉列表

c# - 带有布局的自定义错误页面

c - 我怎么知道分配的空间已成功释放?

memory - 不可撤销的页面

ruby-on-rails - HTTParty 的内存问题和下载大文件