From 01b8030bbe51b954d55c2d5260ebca0402adac51 Mon Sep 17 00:00:00 2001 From: Javed Mohamed Date: Sat, 23 Feb 2019 23:18:22 -0600 Subject: [PATCH] Improve C dynamic memory guide (#23849) - Fix many errors and facts to be more accurate. - Add more examples and cover all four commonly used functions. - Rewrite parts to be more clear. - Add some useful notes and warnings ... memory allocation is error prone! --- .../c/dynamic-memory-management/index.md | 162 ++++++++++++------ 1 file changed, 111 insertions(+), 51 deletions(-) diff --git a/guide/english/c/dynamic-memory-management/index.md b/guide/english/c/dynamic-memory-management/index.md index fb3ff05a8c..08854ef19f 100644 --- a/guide/english/c/dynamic-memory-management/index.md +++ b/guide/english/c/dynamic-memory-management/index.md @@ -1,34 +1,45 @@ --- title: Dynamic Memory Management --- + # Dynamic Memory Management Sometimes you will need to allocate memory spaces in the heap also known as the dynamic memory. This is particulary useful when you do not know during compile time how large a data structure (like an array) will be. + ## An Example -Here's a simple example where we allocate an array asking the user to choose the dimension +Here's a simple example where we allocate an array, asking the user to choose the size. + ```C #include #include int main(void) { - int arrayDimension,i; - int* arrayPointer; - - printf("Please insert the array dimension:"); - scanf("%d",&arrayDimension); - arrayPointer = (int*)malloc(sizeof(int)*arrayDimension); - - if(arrayPointer == NULL){ - printf("Error allocating memory!"); - return -1; - } - - for(i=0;i