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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…