我正在使用一种没有本机堆栈类型的晦涩语言,所以我实现了自己的。现在,在网上阅读我发现了一些不同的方法来做到这一点。
这是我的实现(伪代码)
//push method
function Push(int)
{
Increase (realloc) stack by 4 bytes;
Push int into the new memory area;
}
//pop method
function Pop()
{
collect int from the top of the stack;
reallocate (realloc) the stack to shrink it by 4 bytes;
return int;
}
现在有些人说在弹出一个值后使用 realloc() 调用来调整堆栈的大小对性能不利,所以我有几个问题:
- 最好只使用 malloc 增长堆栈然后在程序结束时释放它?
- 要调整堆栈大小(推送),最好增加 4 个字节或更多?
- 通过在填充时分配的内存加倍来增加堆栈是最佳实践吗?
- 你对上面的代码有什么想法?