gpt4 book ai didi

c++ - avr-gcc 上的自动释放

转载 作者:搜寻专家 更新时间:2023-10-31 01:13:42 24 4
gpt4 key购买 nike

为 8 位 AVR 微 Controller 编程我遇到了一种行为显示在此代码上:

  class classA
{
public:
classA(Display *d) : _d(d) { _d->println("classA()", 0); }
~classA() { _d->println("~classA()", 1); }
uint8_t array[200];
Display *_d;
};
void useClassA(classA *a)
{
a->array[3] = 5;
}
void SomeClass::start()
{
SYSTEM_DISPLAY_FREE_RAM();
debugMethod();
_ui->lcd().println("after debugMethod", 3);
SYSTEM_WAIT_DEBUG_BUTTON();
SYSTEM_DISPLAY_FREE_RAM();
}
void SomeClass::debugMethod()
{
_ui->lcd().println("entered debugMethod", 3);
SYSTEM_WAIT_DEBUG_BUTTON();
SYSTEM_DISPLAY_FREE_RAM();

_ui->lcd().println("before while", 3);
SYSTEM_WAIT_DEBUG_BUTTON();
volatile uint8_t i = 1;
while (i != 0)
{
classA cA(&_ui->lcd());
SYSTEM_DISPLAY_FREE_RAM();
cA.array[199] = i--;
useClassA(&cA);
}
_ui->lcd().println("after while", 3);
SYSTEM_WAIT_DEBUG_BUTTON();
SYSTEM_DISPLAY_FREE_RAM();
}

SYSTEM_DISPLAY_FREE_RAM() 按照中所述计算可用 RAM http://jeelabs.org/2011/05/22/atmega-memory-use/ .当执行到达 SomeClass::start() 时,我得到以下输出:

  Free Ram: 2677
entered debugMethod
Free Ram: 2458
before while
classA()
Free Ram: 2458
~classA()
after while
Free Ram: 2458
after debugMethod
Free Ram: 2677

尽管 classA 对象是在 while 中创建和销毁的,内存似乎是在 debugMethod() 开始时分配的,并且仍然存在直到方法结束。我希望只在内部分配内存同时,因此有一个带有 Free Ram: 2458 的单一打印。

对发生的事情有任何解释吗?

有没有办法强制分配发生在 while 内,而不用使用 new 关键字?

使用的编译器:avr-gcc (WinAVR 20100110) 4.3.3

最佳答案

通常,整个函数的栈帧是在函数的开头分配的。您可以尝试 gcc 参数 --param min-pretend-dynamic-size=100它将尝试为超过 100 字节的对象动态分配和释放堆栈 [1]。

gcc 可以使用 -S 开关向您显示汇编代码,查看它以了解发生了什么,以及 --param min-pretend-dynamic-size 是否有对您的平台和功能的任何影响。

您的情况的另一种解决方案是将 while() 循环的主体移动到一个新函数中,因为这将创建/销毁包含 classA 对象的堆栈帧。

[1] gcc 文档:

最小假装动态大小

Force any automatic object whose size in bytes is equal to or greater than the specified value to be allocated dynamically, as if their size wasn't known to compile time. This enables their storage to be released at the end of the block containing them, reducing total stack usage if multiple functions with heavy stack use are inlined into a single function. It won't have any effect on objects that are suitable for allocation to registers (i.e., that are sufficiently small and that don't have their address taken), nor on objects allocated in the outermost block of a function. The default, zero, causes objects whose sizes are known at compile time to have storage allocated at function entry.

关于c++ - avr-gcc 上的自动释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12198064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com