C ++: defining a local array compared to calling malloc

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 another suitable than the other?

Thank you all for your answers. here is the summary:

  • ex. 1 - heap distribution
  • ex. 2 - stack distribution
  • there is a limit on the size of the stack, use it for smaller allocations
  • you need to free a bunch or it will flow
  • stack allocation is not available after exiting a function
  • heap allocation is available until you free it (or the application ends)
  • VLAs are not part of standard C ++

Corrections are welcome.

Here is an explanation of the difference between a heap and a stack:
What and where is the stack and the heap?

+5
source share
5

, , , . , malloc.

, , , , malloc go. > 16 , , , . kb/mb - .

+5

. , , . , , .

. , . , .

+6

. . , function(). - , , , . , , , ..

. , ++-, new malloc(),

output = new char[len+1];

len * 2 + 1 ? , - , , Unicode . unicode, , , char - , 8- . , , .

+5

:

  • .
  • .

: , :

  • .
  • 10% . Windows Linux 1 2 . , 100 000 .
+3

++, C, ++. C (99).

, "len" , .

malloc() ( ++ 'new') , , () ( "", "" ) ().

, . , , .

, ( ++ RAII, ), , .

, "", :

static char output[(len * 2) + 1];

, , , .

Finally, do not use malloc in C ++ unless you have a really good reason (i.e. realloc). Instead, use the "new" and the accompanying "delete".

+1
source

All Articles