user8241903
user8241903

Reputation:

Which is more efficient : char a[10]; OR char *a; a = malloc(10);

i notice in a function this will not work:

char a[10];
sprintf(a, "test");
return a;

but this works:

char *a;
a = malloc(10);
sprintf(a, "test");
return a;

QUESTION: if i do not have to "return a;"..
is it better to use "char a[10];" ? if so. why ?

Upvotes: 1

Views: 76

Answers (2)

tofro
tofro

Reputation: 6063

malloc is a function call into the standard library. Depending on current heap fragmentation and heap organisation of the compiler, this may be an expensive operation (even the call into the library alone may consume more CPU cycles than a stack allocation).

char a[10] is an increment of the stack frame (rather: works out to a simple subtraction of 10 from the current stack pointer).

Stack allocation is definitively faster on most non-exotic architectures.

Upvotes: 2

Mike Nakis
Mike Nakis

Reputation: 61986

Yes, if you do not have to return a; or store a reference to a anywhere outside of the function, then a is only going to be used locally within the function, so it is perfectly fine to declare a as a local variable. That's precisely why they are called local variables.

Also, declaring a as a local will incur a zero performance penalty, in contrast to malloc() which is rather slow.

Upvotes: 2

Related Questions