Home  >  Article  >  Backend Development  >  Usage of malloc function

Usage of malloc function

步履不停
步履不停Original
2019-06-14 09:55:1443437browse

Usage of malloc function

The full name of malloc is memory allocation, which is called dynamic memory allocation in Chinese. It is used to apply for a continuous memory block area of ​​a specified size and returns the allocated memory area address in void* type. When it cannot When you know the specific location of the memory, if you want to bind the real memory space, you need to dynamically allocate memory.

void* type represents an untyped pointer. C, C stipulates that the void* type can be cast to a pointer of any other type through type conversion.

Generally needs to be paired with the free function.

Function definition

Prototype

extern void *malloc(unsigned int num_bytes);

Header file

#include <stdlib.h>

Function declaration

void *malloc(size_t size);

Remarks: void* Represents a pointer of an undetermined type. void * can point to any type of data. More specifically, it means that when applying for memory space, it is not known what type of data the user will use this space to store (such as char or int or other data). type).

Return value

If the allocation is successful, the pointer to the allocated memory is returned (the initial value in this storage area is uncertain), otherwise the null pointer NULL is returned. When the memory is no longer used, the free() function should be used to release the memory block. The pointer returned by the function must be properly aligned so that it can be used with any data object.

Explanation

Regarding the prototype of this function, malloc previously returned a char pointer. The new ANSIC standard stipulates that this function returns a void pointer, so type conversion is required if necessary. . It can apply to the system to allocate a memory block with a length of num_bytes (or size) bytes.

Generally it needs to be paired with the free function. The free function can release a dynamically allocated address, indicating that this dynamically allocated memory is no longer used, and returns the previously dynamically applied memory to the system.

Related functions

calloc, realloc, free, _alloca.

The difference between new and

Essentially speaking, malloc (for specific implementation on Linux, please refer to man malloc, glibc is implemented through brk()&mmap()) is libc For a function implemented in it, if stdlib.h is not included directly or indirectly in the source code, then gcc will report an error: 'malloc' was not declared in this scope. If the target file is generated (assuming dynamically linked malloc), if there is no libc on the running platform (for Linux platform, just manually specify LD_LIBRARY_PATH to an empty directory), or there is no malloc function in libc, then it will be executed at runtime (Run-time) Something went wrong. New is not the case. It is a keyword of c and is not a function itself. new does not depend on the header file. The c compiler can compile new into target code (g 4.6.3 will insert the _Znwm function into the target. In addition, the compiler will also insert the corresponding constructor according to the type of the parameters) .

In terms of use, malloc and new have at least two differences: new returns a pointer of the specified type and can automatically calculate the required size. For example:

int *p;
p = new int;
//返回类型为int *类型(整数型指针),分配大小为sizeof(int);

or:

int *parr;
parr = new int[100];
//返回类型为int *类型(整数型指针),分配大小为sizeof(int) * 100;

However, with malloc, we must calculate the number of bytes and force conversion to a pointer of the actual type after returning.

int *p;
p = (int*)malloc(sizeof(int) * 128);
//分配128个(可根据实际需要替换该数值)整型存储单元,
//并将这128个连续的整型存储单元的首地址存储到指针变量p中
double *pd = (double*)malloc(sizeof(double) * 12);
//分配12个double型存储单元,
//并将首地址存储到指针变量pd中

First, the malloc function returns the void * type.

For C, if you write: p = malloc (sizeof(int)); then the program cannot be compiled and an error message will be reported: "void* cannot be assigned to an int * type variable".

So you must pass (int *) to cast. For C, there is no such requirement, but in order to make C programs more convenient to transplant into C, it is recommended to develop the habit of forced conversion.

Second, the actual parameter of the function is sizeof(int), which is used to specify the required size of an integer data.

You need to pay attention to a special case of malloc(0). The return value may be a NULL or a valid address (it can be safely freed, but cannot be dereferenced). Note that malloc(-1) is not prohibited. The parameter is an unsigned type. If it is a negative number, it may be converted into a very large positive number. In the end, NULL is usually returned because there is not a large enough memory block.

In the standard program, we need to use malloc and free in this format:

type *p;
if(NULL == (p = (type*)malloc(sizeof(type))))
/*请使用if来判断,这是有必要的*/
{
    perror("error...");
    exit(1);
}
.../*其它代码*/
free(p);
p = NULL;/*请加上这句*/

malloc can also achieve the effect of new [] and apply for a continuous memory. The method is nothing more than It specifies the memory size you need.

For example, if you want to allocate 100 int type spaces:

int *p = (int*)malloc(sizeof(int) * 100);
//分配可以放得下100个整数的内存空间。

Another difference that cannot be seen directly is that malloc only allocates memory and cannot initialize the resulting memory, so we get In a new piece of memory, its value will be random.

Except for the different allocation and final release methods, the pointer is obtained through malloc or new, and other operations are consistent.

Make a special case to supplement it

char *ptr;
if((ptr = (char*)malloc(0)) == NULL)
    puts("Gotanullpointer");
else
    puts("Gotavalidpointer");

At this time, you may get Got a valid pointer, or you may get Got a null pointer.

Working Mechanism

malloc函数的实质体现在,它有一个将可用的内存块连接为一个长长的列表的所谓空闲链表。调用malloc函数时,它沿连接表寻找一个大到足以满足用户请求所需要的内存块。然后,将该内存块一分为二(一块的大小与用户请求的大小相等,另一块的大小就是剩下的字节)。接下来,将分配给用户的那块内存传给用户,并将剩下的那块(如果有的话)返回到连接表上。调用free函数时,它将用户释放的内存块连接到空闲链上。到最后,空闲链会被切成很多的小内存片段,如果这时用户申请一个大的内存片段,那么空闲链上可能没有可以满足用户要求的片段了。于是,malloc函数请求延时,并开始在空闲链上翻箱倒柜地检查各内存片段,对它们进行整理,将相邻的小空闲块合并成较大的内存块。如果无法获得符合要求的内存块,malloc函数会返回NULL指针,因此在调用malloc动态申请内存块时,一定要进行返回值的判断。

Linux Libc6采用的机制是在free的时候试图整合相邻的碎片,使其合并成为一个较大的free空间。

程序示例

正常程序

typedef struct data_type{
    int age;
    char name[20];
}data;
data*bob=NULL;
bob=(data*)malloc(sizeof(data));
if(bob!=NULL)
{
    bob->age=22;
    strcpy(bob->name,"Robert"); 
    printf("%s is %d years old.\n",bob->name,bob->age);
}
else
{
    printf("mallocerror!\n");
    exit(-1);
}  
free(bob);
bob=NULL;

输出结果:Robert is 22 years old.

内存泄漏实例

#include <stdio.h>
#include <malloc.h>
#define MAX 100000000int main(void)
{
    int *a[MAX] = {NULL};
    int i;
    for(i=0;i<MAX;i++)
    {
    a[i]=(int*)malloc(MAX);
    }
    return 0;
}

注:malloc申请之后没有检测返回值。

推荐教程:C#视频教程

The above is the detailed content of Usage of malloc function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn