Home >Backend Development >C#.Net Tutorial >How to use malloc in c language
Usage of malloc() in C language
malloc() is a function used for dynamic memory allocation in the C language standard library. It allocates a memory block of a specific size and returns a pointer to the block.
Syntax:
<code class="c">void *malloc(size_t size);</code>
Parameters:
size
: The memory to be allocated Size (in bytes). Return value:
If the allocation is successful, malloc() will return a pointer to the starting address of the allocated memory block. If the allocation fails (for example, there is not enough memory available), it returns NULL.
Usage:
Allocate memory:
Use allocated memory:
Release allocated memory:
Example:
<code class="c">#include <stdio.h> #include <stdlib.h> int main() { int *ptr; // 分配 10 个 int 大小的内存块 ptr = (int *)malloc(10 * sizeof(int)); // 检查分配是否成功 if (ptr == NULL) { perror("malloc failed"); exit(EXIT_FAILURE); } // 使用已分配的内存 ptr[0] = 10; printf("ptr[0] = %d\n", ptr[0]); // 释放已分配的内存 free(ptr); return 0; }</code>
Advantages:
Disadvantages:
The above is the detailed content of How to use malloc in c language. For more information, please follow other related articles on the PHP Chinese website!