C zero-based video -46-malloc and free

The basic use of malloc

Malloc function prototype is:

void *malloc( size_t size );
  • size: size pledged to apply the heap space in bytes
  • The return value is a pointer of type void *, the memory will be assigned the first address obtained malloc returns space

The reason why the use of type void * pointer, because malloc space we can not know in advance how to apply for the type. Thus, in general we need to return the pointer value strong turn.

#include <stdlib.h>

int main(int argc, char* argv[])
{
    //申请4字节的空间,作为存储int变量使用
    //申请得到的空间首地址,赋值给pValue指针
    int* pValue = (int*)malloc(4);

    //修改值
    *pValue = 0x11111111;
    return 0;
}

We can also apply for more than one element of address space at the same time:

int main(int argc, char* argv[])
{
    //申请12字节的空间,作为存储3个int变量使用
    //申请得到的空间首地址,赋值给pValue指针
    int* pValue = (int*)malloc(12);

    //修改值
    *pValue = 0x11111111;
    *(pValue+1) = 0x22222222;
    *(pValue+2) = 0x33333333;
    return 0;
}

The basic use free of

Free function prototype is:

void free( void *memblock );

You can see, free no return value, only one parameter, we will apply until heap memory first address passed to free can.

#include <stdlib.h>

int main(int argc, char* argv[])
{
    //申请12字节的空间,作为存储3个int变量使用
    //申请得到的空间首地址,赋值给pValue指针
    int* pValue = (int*)malloc(12);

    //修改值
    *pValue = 0x11111111;
    *(pValue+1) = 0x22222222;
    *(pValue+2) = 0x33333333;

    free(pValue);
    return 0;
}

But be careful, if passed to the free address is not requested prior to heap memory address, an error occurs.

with use malloc sizeof

In practice, malloc sizeof with the general use, to increase readability of the code.

#include <stdlib.h>

int main(int argc, char* argv[])
{
    //申请12字节的空间,作为存储3个int变量使用
    //申请得到的空间首地址,赋值给pValue指针
    int* pValue = (int*)malloc(sizeof(int)*3);

    //修改值
    *pValue = 0x11111111;
    *(pValue+1) = 0x22222222;
    *(pValue+2) = 0x33333333;
    return 0;
}

Memory leak problem

If for heap memory, not only apply for release, it will cause a resource leak.
In some cases, because of non-standard code that can not lead to the release of resources:

void MyFun()
{
    int* pValue = (int*)malloc(12);

    //修改值
    *pValue = 0x11111111;
    *(pValue + 1) = 0x22222222;
    *(pValue + 2) = 0x33333333;
}

int main(int argc, char* argv[])
{
    MyFun();
    return 0;
}

Guess you like

Origin www.cnblogs.com/shellmad/p/11695697.html