Summary of dynamic memory operations based on C language
Click on the blue " Linux " in the upper left corner and select " Set as Star "
Read useful articles for the first time☞ [Dry information] Embedded driver engineer learning route☞ [Dry information] Linux embedded knowledge points-mind map-free access☞【Employment】Job search resume template1
1. Application for stack space
#include <stdlib.h> //头文件
void *malloc(size_t size);//函数
size表示申请的空间字节数
函数的返回值:
成功:返回值空间起始地址
失败:NULL
Features:
Allocate memory space of a specified size;
The allocated memory space is continuous;
Memory needs to be released manually;
malloc and free are used in pairs;
malloc and free do not automatically initialize memory contents
Notice:
The pointer type returned by the malloc function is void*, which means it is a general pointer type. When using the pointer returned by the malloc function, it needs to be cast to the desired pointer type.
Example 1: Apply for space for a string
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
//空间申请
char *str = "asdasd";
char *pb = NULL;
pb = (char *)malloc(sizeof(str));
if(pb == NULL)
{
return;
}
pb = str;
printf("*pb = %s\n",pb);
//释放空间
free(pb);
return 0;
}
Example 2: Apply for space for a value
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
//空间申请
int *pb = NULL;
pb = (int *)malloc(sizeof(int));
if(pb == NULL)
{
return;
}
*pb = 10;
printf("*pb = %d\n",*pb);
//释放空间
free(pb);
return 0;
}
2. Heap space release
#include <stdlib.h>
void free(void *ptr);
ptr需要释放的堆区空间的起始地址
3. memset function
#include <string.h> //头文件
void *memset(void *s, int c, size_t n);//函数
s 就是空间的起始地址
c 空间中每个字节 填充的值,通常为0
n 就是空间的字节宽度
The memset function sets the first n bytes in memory area s to the character value c . This function is usually used to initialize the memory area or clear the memory area.
Case 1:
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char str[10];
memset(str, 'A', 5); // 将str的前5个字节设置为'A'
printf("%s\n", str); // 输出"AAAAA"
return 0;
}
Case 2:
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
int *pb = NULL;
pb = (int *)malloc(sizeof(int));
if(pb == NULL)
{
return;
}
memset(pb,0,n*sizeof(int)); //将堆区空间清0
*pb = 10;
printf("*pb = %d\n",*pb);
//释放空间
free(pb);
return 0;
}
4. calloc function
#include <stdlib.h>
void *calloc(size_t nmemb, size_t size);
nmemb:内存的块数
size:每一块的字节数
返回值:成功为堆区空间起始地址 失败为NULL
calloc会对申请的空间 自动清0
Example:
#include <stdio.h>
#include <stdlib.h>
void Input(int *p, int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
scanf("%d", p + i);
}
}
void Output(int *p, int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
printf("%d ", p[i]);
}
printf("\n");
}
int main(int argc, char const *argv[])
{
int n = 0;
printf("请输入int元素的个数:");
scanf("%d", &n);
//根据元素个数 申请空间
int *p = NULL;
p = (int *)calloc(n, sizeof(int));
if (p == NULL)
{
return;
}
//键盘获取输入
Input(p,n);
//遍历
Output(p,n);
//释放空间
free(p);
return 0;
}
5. realloc function (additional space)
#include <stdlib.h>
void *realloc(void *ptr, size_t size);
ptr:指向要重新分配的内存区域的指针。
newSize:新的内存区域大小(以字节为单位)。
如果成功,它会返回一个指向新的内存区域的指针。如果失败,它会返回NULL。
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int *)malloc(5 * sizeof(int)); // 分配5个整数的内存空间
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// 使用realloc重新分配内存空间,将大小改为10个整数
arr = (int *)realloc(arr, 10 * sizeof(int));
if (arr == NULL) {
printf("Memory reallocation failed.\n");
return 1;
}
// 在新分配的内存空间中存储一些值
for (int i = 0; i < 10; i++) {
arr[i] = i;
}
// 输出数组中的值
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr); // 释放动态分配的内存空间
return 0;
}
6. Memory leakage
When a program fails to properly free memory that is no longer in use. A memory leak causes a program to consume more and more memory until all available memory is exhausted, causing the program to crash or run slowly.
Memory leaks usually occur in the following situations:
Dynamically allocated memory is not released;
Local variables are not released;
The structure or array is not released;
To detect and avoid memory leaks, there are tools and techniques you can use, such as:
-
Use static code analysis tools: These tools can check your code for potential errors, including memory leaks.
-
Use dynamic analysis tools: These tools can detect memory leaks while the program is running. For example, Valgrind is a popular dynamic analysis tool that can detect memory leaks in C programs.
-
Pay attention to memory management when writing code: When writing code, you should pay attention to when memory is allocated and released. Make sure to free dynamically allocated memory promptly when you are finished using it, and avoid using pointers to local variables.
-
Use smart pointers: Smart pointers are a mechanism that automatically manages memory and can automatically release memory at the appropriate time to avoid memory leaks. In C++, you can use smart pointers to manage dynamically allocated memory.
7. Summary
Application for space
malloc(size_t size);//空间申请
calloc(size_t nmemb, size_t size);//空间块申请
use of space
memset(void *s, int c, size_t n);//空间初始化
calloc(size_t nmemb, size_t size);//空间追加
release of space
free(void *ptr);//空间释放
end
A mouthful of Linux
Follow and reply [ 1024 ] Massive Linux information will be given away
Collection of wonderful articles
Article recommendation