c++ - 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";
}
}
}
解决方案
为了补充约翰的答案,
你使用的方式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在哪里?
推荐阅读
- javascript - 如何在 JS 中获取网页的图片
- php - Hubspot CRM API:如何过滤联系人并显示所需的属性
- python - 可执行文件显示即使在 Conda 环境中安装了软件包,也找不到模块
- r - 滚动窗口回归的 T 统计量
- zsh - 管道 fzf 选择到文本操作到 zsh 提示符(不执行)
- pandas - 熊猫取 N 最大忽略 0
- c# - 如何在 UWP 桌面应用程序中使用 Win2D 将文本转换为图像?
- bpf - 比较 BPF 中的字符串时出现错误的地址错误
- django - 我似乎找不到从我的 django 应用程序写入 heroku 的 postgres 的方法
- c# - 如何使用服务帐户检索 Google 群组成员资格?