c++: local array definition versus a malloc call

前端 未结 1 829
南旧
南旧 2020-12-18 01:49

What is the difference between this:

somefunction() {  
    ...  
    char *output;   
    output = (char *) malloc((len * 2) + 1);  
    ...  
}  


        
相关标签:
1条回答
  • 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.

    0 讨论(0)
提交回复
热议问题