What is the difference between this:
somefunction() {
...
char *output;
output = (char *) malloc((len * 2) + 1);
...
}
and this:
somefunction() {
...
char output[(len * 2) + 1];
...
}
When is one more appropriate than the other?
thanks all for your answers. here is a summary:
- ex. 1 is heap allocation
- ex. 2 is stack allocation
- there is a size limitation on the stack, use it for smaller allocations
- you have to free heap allocation, or it will leak
- the stack allocation is not accessible once the function exits
- the heap allocation is accessible until you free it (or the app ends)
- VLA’s are not part of standard C++
corrections welcome.
here is some explanation of the difference between heap vs stack:
What and where are the stack and heap?
Use locals when you only have a small amount of data, and you are not going to use the data outside the scope of the function you’ve declared it in. If you’re going to pass the data around, use malloc.
Local variables are held on the stack, which is much more size limited than the heap, where arrays allocated with malloc go. I usually go for anything > 16 bytes being put on the heap, but you have a bit more flexibility than that. Just don’t be allocating locals in the kb/mb size range – they belong on the heap.