For an embedded piece of code (avr-gcc) I am trying to reduce stack memory usage. So what I want to do is create a pointer, pass it to a function, and in the function, change the address the pointer points to, to the address of a heap allocated variable. This way, there would be no stack memory allocated inside main()
for the testPointer
.
I am trying it with the following code
#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;
}
but the testPointer address doesn't get reassigned. Of course in the real world use-case myfunc2
wouldn't be as simple, but it is returning a pointer to a heap allocated character array.
Output:
hello: 0x404030
test: 0x7ffe48724d38
test: 0x7ffe48724d38
test value: (null)