Dynamic memory allocation involves the concept of a stack: the stack is two data structures. Stacks are data structures that are ordered by data items and can be inserted and deleted only at one end, called the top of the stack.
Stack (operating system): Automatically allocate the release by the operating system, store the function's parameter value, the local variable's value and so on. The operation is similar to the stack in the data structure.
Heap (operating system): typically assigned by programmers to release, if the programmer does not release, the program at the end may be reclaimed by the OS, the allocation is similar to the linked list.
in the C language, global variables are assigned to static storage in memory, and non-static local variables, including formal parameters, are dynamic stores that are allocated in memory, called stacks. In addition, the C language also allows the establishment of a dynamic memory allocation area to hold some temporary data, which need not be defined in the declaration part of the program, and do not have to wait until the end of the function to release, but need to open at any time, do not need to be released at any time. These verses temporarily exist in a special free storage area called the heap area. The
system provides four library functions to implement dynamic memory allocation:
(1) malloc (size) allocates a contiguous space of size in the dynamic storage area of memory.
(2) calloc (n,size) allocates n contiguous spaces of size in the dynamic storage area of memory. The
(3) free (p) frees the dynamic space that the pointer variable p does point to. The
(4) realloc (p,size) changes the dynamic space size that the pointer variable p points to to size.
Raise 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] <) printf ("%d", P[i]);
printf ("\ n");
}
Instead of defining an array, the program opens up a dynamic free allocation area, when entering a number, the address is copied to the 5 elements of the dynamic array, P1 points to the first integer data, and when the check function is invoked, the P1 is passed as an argument to the formal parameter p, so it can be understood that the formal parameter p and the argument P1 share a dynamic allocation area.