首页 > 解决方案 > realloc():即使使用 malloc() 分配内存,旧大小也无效

问题描述

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

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

标签: c++memorydynamicmallocrealloc

解决方案


为了补充约翰的答案,

你使用的方式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 ? true : false);您应该简单地使用return arr != nullptr;.

正确的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、赋值运算符和d-tor在哪里?


推荐阅读