Dynamic Memory Allocation
Memory alloc malloc
1. the malloc C library function encapsulates BRK.
2. Int BRK (void * ADDR); LINUX;
Structure:
App
Library lib
API
OS
Hard
Due to alignment, memory allocation may take a multiple of 4.
Int * P;
P = malloc (4); 4 bytes
Void free (void * PTR); // release. The PTR corresponding to malloc is the address for applying for memory blocks. It cannot be known that the execution fails.
# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Int * P;
Char Buf [32];
P = (int *) malloc (sizeof (INT ));
...
Free (P );
Return 0;
}
Free must release heap memory.
Memory Structure:
Stack local variable function calls from top to bottom 10 m
Space allocated by heap from bottom to malloc
BSS does not have an initialized global variable
Data global variables
Redata constant
Text binary
Recursive stack smash (generating too many stack needles)
When the process ends, the dynamic allocation will be returned to the system.
Free is only autorelease
When you apply for n Bytes of space, there are more than N spaces. The previous management structure (4 bytes)
Malloc 8-byte alignment
1000 8
10000 16
24, 11000
The last three digits are 0.
Therefore, the last three digits of the 4-byte management mechanism are 0.
The last digit indicates whether the memory is available. 0 indicates that 1 is unavailable.
Int main (INT argc, char * argv [])
{
Int * P, * q;
Int N;
N = atoi (argv [1]); // string-> int
P = (int *) malloc (N );
Q = (int *) malloc (8 );
Printf ("% x, % d/N", P [-1], (unsigned) q-(unsigned) P); // P [-1] is the management structure
Free (P );
Free (Q );
}
If 16 bytes are allocated, 20 bytes need to be allocated, but cannot be fully divided by 8, SO 4 bytes are filled.