2-16 malloc (1)

Source: Internet
Author: User

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.
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.