【发布时间】:2020-01-25 06:28:40
【问题描述】:
对于一段嵌入式代码 (avr-gcc),我正在尝试减少堆栈内存使用量。所以我想做的是创建一个指针,将它传递给一个函数,然后在函数中,将指针指向的地址更改为堆分配变量的地址。这样,main() 内部就不会为 testPointer 分配堆栈内存。
我正在尝试使用以下代码
#include <stdio.h>
char hello[18] = "Hello cruel world";
char* myfunc2() {
return hello;
}
void myfunc(char *mypointer) {
mypointer = myfunc2();
}
int main(){
char *testPointer;
printf("hello: %p\n", &hello);
printf("test: %p\n", &testPointer);
myfunc(testPointer);
printf("test: %p\n", &testPointer);
printf("test value: %s\n", testPointer);
return 0;
}
但 testPointer 地址不会被重新分配。当然,在现实世界中,myfunc2 的用例不会那么简单,但它返回一个指向堆分配字符数组的指针。
输出:
hello: 0x404030
test: 0x7ffe48724d38
test: 0x7ffe48724d38
test value: (null)
【问题讨论】:
-
你需要研究一下静态存储和堆的区别。您的 AVR 程序中应该没有堆,并且此源中没有堆分配。此外,做你试图减少堆栈使用的方法是无稽之谈。相反,您应该专注于实际杀死 MCU 上所有内存的原因,首先将 stdio.h 扔到它所属的垃圾中。
标签: c