2-16 malloc (1)

Source: Internet
Author: User

Dynamically allocating memory
Memory Alloc malloc
The 1.malloc C library function internally encapsulates the BRK.
2.int brk (void *addr); Linux

Structure:
App
Library Lib
Api
OS
Hard


Due to alignment, memory may be allocated in multiples of 4
int *p;
P=malloc (4); 4 bytes
void free (VOID*PTR);//release, and malloc correspond to PTR as the address of the block of application memory, which cannot be known to execute unsuccessfully.

#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 the heap memory.

Memory structure:
Stack local variable function call from top down 10M
Heap the space allocated from the bottom up malloc
BSS does not initialize global variables
Data global variable
Redata Constants
Text binary

Recursive stack smash (produces too many stack pins)

When the process is finished, dynamic allocation is returned to the system.
Free is just autorelease.

When you request n bytes of space, more than n space, preceded by a management structure (4 bytes)

malloc 8-byte alignment
1000 8
10000 16
11000 24
The latter three digits are 0.
So the 4-byte management mechanism of the latter three digits is 0
The last one shows whether memory is available. 0 indicates that No 1 is available

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] for management structure
Free (p);
Free (q);
}

If you allocate 16 bytes, you need to allocate 20 bytes, but not divisible by 8, so 4 bytes are populated.

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.