Reputation: 176
Edit : edited my question. Thanks to @SomeProgrammerDude for helping me understand what I did wrong, (I was confounding arrays and pointers, here is a relevant topic that helped me : Difference between array type and array allocated with malloc).
Let's say I have an array 'a' declared and initialized inside a function, if I declare a pointer 'b' outside of the function and try to return 'a' casted as a pointer :
uint8_t *b;
uint8_t * foo(void){
unint8_t a[size] = {'a', 'b', ...};
return (uint8_t *) a;
}
b = foo(b);
Why do I get :
warning: function returns address of local variable [-Wreturn-local-addr]
Upvotes: 0
Views: 278
Reputation: 409266
I'm kind of guessing here since it's not that clear exactly what you wonder about, but I think you're asking about if a
and b
both point to the same memory after the assignment c = a
?
In that case the answer is yes.
+---+ +-------------------------------+ | a | --> | Memory allocated by malloc... | +---+ +-------------------------------+
If we look at it kind of graphically, after a = malloc(...)
you have something like
+---+ +-------------------------------+ | a | --> | Memory allocated by malloc... | +---+ +-------------------------------+
Then after the assignment c = a
you have something like
+---+ | a | --\ +---+ \ +-------------------------------+ >--> | Memory allocated by malloc... | +---+ / +-------------------------------+ | c | --/ +---+
And after the return c
, with b = foo(b)
then you have only
+---+ +-------------------------------+ | b | --> | Memory allocated by malloc... | +---+ +-------------------------------+
Important note: Unless you know the size of the allocated memory some other way, using the memory allocated could be troublesome, since you don't know where it ends. Going out of bounds leads to undefined behavior.
However, as long as you stay in side the bounds of the allocated memory, you can use it any way you please. You can write to it or you can read from it, by dereferencing the pointer b
.
Another important note: The passing of the argument to foo
is irrelevant, the foo
function could just as easily do return a
and not bother with the argument, and the end-result (b
pointing to the memory) would be just the same:
uint8_t foo(void)
{
uint8_t *a = malloc(...);
return a;
}
And the variable a
isn't even needed:
uint8_t foo(void)
{
return malloc(...);
}
With both of these functions above, the end result after b = foo()
would still be
+---+ +-------------------------------+ | b | --> | Memory allocated by malloc... | +---+ +-------------------------------+
Upvotes: 1