C language dynamic memory allocation details

  • 2020-05-26 09:40:23
  • OfStack

C language dynamic memory allocation details

Dynamic memory allocation involves the concept of a stack: a stack is two data structures. The stack is a data structure in which data items are arranged in order and can only be inserted and deleted at end 1 (known as the top of the stack (top)).

Stack (operating system) : by the operating system automatically allocated release, stored function parameter values, local variable values, etc. It operates like a stack in a data structure.

Heap (operating system) : 1 is normally allocated and released by the programmer. If the programmer does not release, the program may be recovered by OS at the end. The allocation is similar to a linked list.

\ in C, global variables are allocated to a static storage area in memory, while non-static local variables (including formal parameters) are allocated to a dynamic storage area in memory, which is called a stack. In addition, the c language also allows the creation of a dynamic memory allocation area to hold temporary data that is not defined in the declared part of the program or released at the end of the function, but is available when needed, not at any time. These verses are temporarily stored in a special free storage area called the heap area.

The system provides four library functions to realize the dynamic allocation of memory:

(1) malloc(size) allocates a continuous space of length size in the dynamic storage area of memory.
(2) calloc(n,size) allocates n continuous Spaces of length size in the dynamic storage area of memory.
(3) free(p) releases the pointer variable p to do pointing to the dynamic space.
(4) realloc(p,size) changes the size of the dynamic space pointed by the pointer variable p to size.

Take a chestnut:


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

int main()
{
  void check(int *);
  int *p1, i;
  p1 = (int *)malloc(5*sizeof(int));
  for ( i = 0; i < 5; i++)
   scanf("%d",p1+i);
  check(p1);
  getchar();
  getchar();
  return 0;
}
void check(int *p)
{
  int i;
  for (i = 0; i < 5; i++)
  if (p[i] < 60) printf("%d", p[i]);
  printf("\n");
}

Program does not define an array, but opens up 1 dynamic free allocation area, enter the number, according to the address copy to dynamic array of five elements, p1 pointing to the first integer data, call check function, p1 as arguments passed to the parameter p, therefore can be understood as a parameter p and arguments p1 male 1 period of dynamically allocated area.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: