int a[1000];
int *c;
void foo(void)
{
int b[1000];
memcpy(b, someConstArray, 1000);
c = (int *)malloc(sizeof(b));
memcpy(c, b, 1000);
}
void bar(void)
{
memcpy(a, someConstArray, 1000);
c = (int *)malloc(sizeof(a));
memcpy(c, a, 1000);
}
I know this has been asked quite a number of times, but I need to know what the performance difference between auto allocation vs static allocation, e.g. a vs b, in relative to each other. Does declaring the a this way take performance hit because of locality?
Compile in gcc for embedded systems.
PS: I am aware that it is a redundant and useless function. The main question is how does the variable allocation affects performance
Inchar* foo(void)you return an invalid pointer, becausebceases to exist when you exit the function.Both allocations have the same performance
, it’s just the way you use them is incorrect.bis allocated on the stack when the functionfoois being called (the performance is of simply changing the value of the stack pointer). It’s deallocated whenfoois done (by changing the stack pointer, again).ais allocated somewhere (global, I’m guessing, or on stack in some other context), and there’s no performance hit there as well.If you need to allocate memory within your function that should be given to the caller (as in your
foo) – then the allocation should be dynamic – usingmalloc(ornewif C++). Then there’s indeed a performance hit, depending on the relevant memory manager performance.