Home Backend Development C#.Net Tutorial Usage of malloc function

Usage of malloc function

Jun 14, 2019 am 09:55 AM
malloc function

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);
Copy after login

Header file

#include <stdlib.h>
Copy after login

Function declaration

void *malloc(size_t size);
Copy after login

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);
Copy after login

or:

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

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中
Copy after login

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;/*请加上这句*/
Copy after login

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个整数的内存空间。
Copy after login

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");
Copy after login

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;
Copy after login

输出结果:Robert is 22 years old.

内存泄漏实例

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

注: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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles