Possible Duplicate:
Difference between declaration and malloc
what's the difference between:
char * a = malloc(size);
and
char a[size];
Is one better than the other? is there any advantage at all in using malloc?
Possible Duplicate:
Difference between declaration and malloc
what's the difference between:
char * a = malloc(size);
and
char a[size];
Is one better than the other? is there any advantage at all in using malloc?
You don't control the life-time scope of stack allocated memory, it's only valid for as long as the scope (unless you make it static).
malloc
is for allocating memory on the heap. It's valid until you call free
on that memory.
It's faster to allocate memory on the stack, normally because you're not actually allocating new memory you're just reserving more of what you're already using but you don't control the life-time, it controlled by the scope of your block or function.
what's the difference between
char *a = malloc(size);
and char *a[size];`?
The first one declares a pointer to char
and allocates size
bytes for it on the heap. The second one allocates size
pieces of char
pointers. They're not equivalent.
Is the one better than the other?
No, they have different uses.
Is there any advantage at all in using
malloc()
?
Yes. If you want to return an array from a function, you can't do this:
char a[size];
return a;
because then a
is out of scope after the return, and using it results in undefined behavior. So in this case you must use
char *a = malloc(size);
return a;
(Generally this is the case, since you would presumably want to return a new string each time from a function - however, if this is not a requirement, you can use a static array, declared locally.)
However, if the array is only to be used locally, then it's generally advisable to use auto (stack) arrays and not malloc()
because that avoids increasing memory fragmentation and stack operations can be faster than heap access.