← Back to Index
Research & Engineering Archive

LPC 8. Dynamic Memory Allocation

By Jingnan Huang · March 07, 2025 · 971 Words

Last Edit: 3/7/25

前面提到过了 Array 中的 Memory 的分配方式是固定的连续内存,而想要修改 Array 的大小则变得困难,这时候就需要通过 Dynamic Memory Allocation 来动态的分布内存

8.1 Dynamic Memory Allocation
#

8.1.1 Different Options when array size is unknown
#

Code
#

Const + Global
#

Heap
#

Stack
#

Stack Overflow 栈溢出
#

Variable Size Array
#

#include <stdio.h>
int main(void) {
  int size;
  printf("Enter size of array: ");
  scanf("%d", &size);
  int arr[size];
  printf("Array allocated from %p to %p", arr, arr+size);
  return 0;
}

Dynamically Allocate Memory
#

Memory Leak
#

#include <stdio.h>
#include <stdlib.h>

double getAverage(int);

int main(void) {
  int size;
  printf("Enter size of array:");
  scanf("%d", &size);
  double avg = getAverage(size);
  printf("Average is %.2lf\n", avg);
  return 0;
}

double getAverage(int size) {
  int* myArray = (int*)malloc(size * sizeof(int));

  printf("Enter grades:");
  for (int index = 0; index < size; index++) {
    scanf("%d", &myArray[index]);
  }
  int sum = 0;
  for (int index = 0; index < size; index++) {
    sum += myArray[index];
  }
  return (double)sum / size;
}
#include <stdio.h>
  #include <stdlib.h>
  
  double getAverage(int);
  
  int main(void) {
    int size;
    printf("Enter size of array:");
    scanf("%d", &size);
    double avg = getAverage(size);
    printf("Average is %.2lf\n", avg);
    return 0;
  }
  
  double getAverage(int size) {
    int* myArray = (int*)malloc(size * sizeof(int));
    
    printf("Enter grades:");
    for (int index = 0; index < size; index++) {
      scanf("%d", &myArray[index]);
    }
    int sum = 0;
    for (int index = 0; index < size; index++) {
      sum += myArray[index];
    }
    free(myArray);
    myArray = NULL;
    return (double)sum / size;
  }