C-language learning notes-dynamic memory allocation

Source: Internet
Author: User

1. Meaning of dynamic memory allocation

(1) All operations in the C language are memory-based.

(2) Variables and arrays are aliases of memory.

① memory allocations are determined by the compiler during compilation

② You must specify the array length when defining an array

The length of the ③ array must be determined at compile time.

(3) However, some additional memory space may be required during the process of running the program

2. malloc and FREE functions

(1) malloc and free to perform the release of dynamic memory allocations

(2) malloc allocates a contiguous amount of memory

(3) malloc is in bytes, and the return value does not take any type information: void* malloc (size_t size);

(4) Free to return dynamic memory to the system: void free (void* pointer);

(5) _msize (void* pointer) can get malloc out of memory space size

3. Places to be aware of using malloc and free

(1) malloc and free are library functions, not system calls

(2) malloc may actually allocate more memory than requested, but cannot rely on malloc behavior on different platforms.

(3) malloc returns NULL when the requested dynamic memory is not satisfied

(4) when the parameter of free is NULL, the function returns directly

What does malloc (0) return?

#include <stdio.h>#include<malloc.h>intMain () {intI=Ten; int* p=NULL;  for(i=0;i< -; i++)    {        //Note that malloc (0) returns a valid memory address with a size of 1//but we can't rely on the compiler's behavior to use this byte of space! p = (int*)malloc(i); printf ("%d", _msize (p));//returns the amount of memory space that malloc comes out of         Free(P); }    return 0;}

Memory Leak Detection Module

Mleak.h

#ifndef _mleak_h_ #define _mleak_h_<stdio.h><malloc.h>#define malloc (n) Mallocex (n, __file__, __line__)#define free (p) Freeex (p)voidconstchar  Const line ); void Freeex (void* p); void print_leak_info (); #endif

Mleak.c

#include"mleak.h"#defineSIZE 256//dynamic Memory Request parameter structure bodytypedefstruct{    void* pointer;//the memory address that was applied to    intSize//memory block Size    Const Char* file;//file name    intLine//File line number}mitem;StaticMitem G_record[size];//record the operation of each dynamic memory requestvoid* Mallocex (size_t N,Const Char* File,ConstLine ) {    inti =0; void* ret =malloc(n);//Dynamic Memory Request        if(Ret! =NULL) {        //If the application is successful, record it.//iterate through the global array and record this operation         for(i =0; i< SIZE; i++)        {            //Find Location            if(G_record[i].pointer = =NULL) {G_record[i].pointer=ret; G_record[i].size=N; G_record[i].file=file; G_record[i].line=Line ;  Break; }        }    }        returnret;}voidFreeex (void*p) {    if(P! =NULL) {        inti =0; //Traverse Global Array, free memory space, and clear operation Record         for(i =0; i< SIZE; i++)        {            if(G_record[i].pointer = =p) {G_record[i].pointer=NULL; G_record[i].size=0; G_record[i].file=NULL; G_record[i].line=0;  Free(P);  Break; }        }    }}voidPrint_leak_info () {inti =0; printf ("potenital Memory Leak info:\n"); //traverse the global array to print the request record for the space that is not freed     for(i =0; i< SIZE; i++)    {        //Find Location        if(G_record[i].pointer! =NULL) {printf ("address:%p, size:%d, location:%s:%d\n", G_record[i].pointer, G_record[i].size, g_record[i].fi         Le, G_record[i].line); }     }}

TESTC.

#include <stdio.h>#include"mleak.h"voidf () {//no release, will cause a memory leak! MALLOC ( -); }intMain () {int* p = (int*) MALLOC (3*sizeof(int));        f (); p[0] =1; p[1] =2; p[2] =3;    Free (p);        Print_leak_info (); return 0;}/*output: E:\STUDY>GCC test.c mleak.ce:\study>a.exepotenital Memory Leak info:address:00602ed8, size:100, Location:38-1.c:7*/
4. Calloc and ReAlloc functions

(1) Brothers of malloc:

void* calloc (size_t num, size_t size);

void* realloc (void* pointer,size_t new_size);

(2) The Calloc parameter indicates the memory space to return the size of one of NUM's types, such as sizeof (int). Calloc can request memory in type size and initialize to 0.

(3) ReAlloc is used to modify the size of a memory block that has previously been allocated. When the first parameter is pointer to NUL, it is equivalent to malloc.

Use of Calloc and realloc

#include <stdio.h>#include<malloc.h>#defineSIZE 5intMain () {inti =0; int* PI = (int*)malloc(SIZE *sizeof(int));//malloc memory is not initialized     Short* PS = ( Short*)calloc(SIZE,sizeof( Short));//memory initialized to 0     for(i =0; I < size;i++) {printf ("pi[%d] =%d, ps[%d] =%d\n", I, pi[i], I, ps[i]); } printf ("Before:pi =%p\n", PI);//pi pointer before resetting memory sizePI= (int*)realloc(PI,2* SIZE *sizeof(int));//the memory is not initializedprintf ("After:pi =%p\n", PI);  for(i =0; I <Ten; i++) {printf ("pi[%d] =%d\n", I, pi[i]); }     Free(PI);  Free(PS); return 0;}

Resources:
Www.dt4sw.com
Http://www.cnblogs.com/5iedu/category/804081.html

C-language learning notes-dynamic memory allocation

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.