当前位置:网站首页>Dynamic memory development
Dynamic memory development
2022-07-25 01:27:00 【Blue cat Knight】
1. Introduction
int a = 10; Apply to memory 4 Bytes int arr[20] ; Apply to memory 80 Bytes ;
The above-mentioned way of opening up space has two characteristics :
1. The size of the space opening is fixed .
2. Arrays are declared , You must specify the length of the array , The memory it needs is allocated at compile time .
But the need for space , It's not just that . Sometimes the amount of space we need is known when the program is running ,
The way to open up space when compiling arrays is not enough .
At this time, you can only try dynamic storage development .
2. Dynamic memory functions malloc free realloc calloc
1.malloc void* malloc (size_t size);
Allocate one byte of memory space , Returns a pointer to the beginning of the block .
Parameters size
The size of the memory space , In bytes . Is an unsigned integer type .size_t
Return value
success , Pointer to the memory block allocated by the function .
This pointer is always of type , It can be converted to a data pointer of the desired type , So that you can dereference .
If the function fails to allocate the requested memory block , Then return to Null pointer .
We use code to explain in detail
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
int main()
{
// Dynamic memory management
//malloc free calloc realloc
int arr[10] = { 0 };
// Dynamic memory development
int*p = (int*)malloc(40); // convert to (int*) type
if (p == NULL) // Opening up space may fail Use here to judge
{
printf("%s\n", strerror(errno));
return 1; // return 1 Indicates that the exception returns
}
// It's a success
// Use
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));
}
// Notice that there is no free Can cause memory leaks Leave a foreshadowing
return 0;
}
2.free void free (void* ptr);
Free up allocated memory space
Parameters
Point to previously used or Pointer to the allocated memory block .malloc realloc calloc( It can also be NULL Just don't release it )
Return value
nothing
Let's still use code to introduce in detail ;
int main()
int arr[10] = { 0 };
// Dynamic memory development
int*p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// It's a success
// No, free When
// It does not mean that memory space is not recycled
// When the program exits , The system will automatically Reclaim memory space
free(p); // Free up memory however p Or a pointer
// Still available p Come and visit us just Free memory
// If the memory just released has been allocated At this time, something will go wrong
p = NULL; // So here's for p Assign null pointer
return 0;
}3.calloc void* calloc (size_t num, size_t size);
Open up and Zero initialization The space opened up
Parameters
size_t num : Number of elements
size_t size : The size of each element
Return value
success , Pointer to the memory space allocated by the function .
This pointer is always of type , It can be converted to a data pointer of the desired type , So that you can dereference .
If the function fails to allocate the requested memory block , Then return to Null pointer .void*
Analyze the code on
int main()
{
int* p = (int*)calloc(10, sizeof(int));
if (p == NULL) // Opening up space may fail Use here to judge
{
printf("%s\n", strerror(errno));
return 1; // return 1 Indicates that the exception returns
}
// It's a success
// Use
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));
}
}The running result shows that 0 therefore It is obvious that initialization has been carried out here

4.realloc void* realloc (void* ptr, size_t size);
Reallocate memory space
Parameters
void*ptr : Point to previously used or Pointer to the allocated memory space . perhaps , It can be a Null pointer , under these circumstances , A new space will be allocated ( It's like being called )( and malloc In the same way ).
size_t size: New size of memory space , In bytes . Is an unsigned integer type .size_t
Return value
Pointer to the reallocated memory block , The memory block may be the same as the new location , It may also be the same as the new location .
The type of this pointer is , It can be converted to a data pointer of the desired type , So that you can dereference .
Code up
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// It's a success
// Use
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i + 1;
}
// Capacity expansion
// realloc(p, 80); // 80 For the total new size
// p = realloc(p,10000000000) // This will turn p Make it a null pointer ; Even the initial space can't be found
int* ptr = (int*)realloc(p, 80);
if (ptr != NULL)
{
p = ptr;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));
}
free(p);
p = NULL;
return 0;
}3. Common dynamic memory errors
1. Cross border access to dynamic open space
Don't talk nonsense , Code up .
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
int i = 0;
for (i = 0; i <= 10; i++) // A cross-border visit
{
p[i] = i; // p[i] amount to *(p+i)
}
free(p);
p = NULL;
return0;
}If it works Will find The program crashed

2. Use free Release a piece of dynamic memory
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
int i = 0;
for (i = 0; i < 10; i++)
{
*p = i;
p++;
}
free(p); //free Released p The pointing position has changed
// Caused the use free The problem of releasing a piece of dynamic development memory
p = NULL;
return 0;
}The same program will crash
3. Multiple releases of the same dynamic memory
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
free(p);
// p == NULL; Without this line of code Then the program will crash
free(p);
return 0;
}4. Dynamic memory forget to release ( Memory leak )
Take on the above The foreshadowing of ha-ha
void test()
{
int* p = (int*)malloc(100);
if(1==1) // Arbitrary judgment expression
{
return ; // perform return And no chance to execute free 了 Will cause memory leaks
}
free(p);
p = NULL;
}4. Classic title
1. Please ask the following operation Test What is the result of the function ?
void GetMemory(char*p)
{
p= (char*)malloc(100); // The function with formal parameters is destroyed And the space is still , Caused a memory leak
}
void Test(void)
{
char* str=NULL;
GetMemory(str); // str Still NULL
strcpy(str, "hello world"); // str yes NULL; It will crash when dereferencing
printf(str);
}
int main()
{
Test();
return 0;
}correct
void GetMemory(char**p)
{
*p= (char*)malloc(100);
}
void Test(void)
{
char* str=NULL;
GetMemory(&str); // discharge str The address of
// Then there is dynamic Opened up 100 Byte address
strcpy(str, "hello world");
printf(str);
// Remember to release
free(str)
str = NULL:
}
int main()
{
Test();
return 0;
}2. Please ask the following operation Test What is the result of the function ?
char* GetMemory(void)
{
char p[] = "hello world";
return p; // The return is h First element address of
}
// After function ends p Be destroyed Back to the operating system
void Test(void)
{
char* str=NULL;
str=GetMemory(); // This is the time str Will be assigned a wild pointer
printf(str);
}
int main()
{
Test();
return 0;
}3. Please ask the following operation Test What is the result of the function ?
void Test(void)
{
char* str= (char*)malloc(100);
strcpy(str, "hello");
free(str); // str For the wild pointer
if(str!=NULL)
{
strcpy(str, "world"); // str 's memory is released Caused illegal access
printf(str);
}
}
int main()
{
Test()
return 0;
}
边栏推荐
- Cloud native observability tracking technology in the eyes of Baidu engineers
- G025-db-gs-ins-02 openeuler deployment opengauss (1 active and 1 standby)
- 7.14 - daily question - 408
- Point to point copy and paste of web pages
- Take the first place in the International Olympic Games in mathematics, physics and chemistry, and win all the gold medals. Netizen: the Chinese team is too good
- Redis transaction learning
- Antdb database products were selected into the global database industry map (2022) of the China Academy of communications and communications
- After burning up 130 billion yuan in ten years, vertical e-commerce will eventually enter the dust of history
- Document the use of anti shake in packaged components and projects
- A string "0" was actually the culprit of the collapse of station b
猜你喜欢

Boutique solution | Haitai cloud password application service solution to create secure and compliant Cloud Applications

Green low-carbon Tianyi cloud, a new engine of digital economy!

Ireport export PDF font bold failure
![[25. Hash table]](/img/c4/1500d070d44d3bd84eb141ed38013d.png)
[25. Hash table]

Kernel structure and design

Latest information of 2022 cloud computing skills competition
![[29. DFS depth is preferred]](/img/f1/f0c4302a1f7c14c206ff0bdf2eed5c.png)
[29. DFS depth is preferred]

2022/7/18-7/19

Open source demo | release of open source example of arcall applet

Create the first hbuilder project
随机推荐
Target segmentation for 10000 frames of video, less than 1.4GB of video memory, open source code | ECCV 2022
Data governance notes
Grpc sets connection lifetime and server health check
G025-db-gs-ins-02 openeuler deployment opengauss (1 active and 1 standby)
Document the use of anti shake in packaged components and projects
Breederdao's first proposal was released: the constitution of the Dao organization
Join MotoGP Monster Energy British Grand Prix!
BisinessCardGen
Harbor installation
Turn: emotional internal friction is the biggest source of inefficiency in your life
record
Take the first place in the International Olympic Games in mathematics, physics and chemistry, and win all the gold medals. Netizen: the Chinese team is too good
Alibaba cloud released the white paper "upgrade - standardization of data warehouse upgrade delivery"
Windows security hardening -- close unnecessary ports
Sort out some scattered knowledge points by yourself
Example analysis of recombinant monoclonal antibody prosci CD154 antibody
[summer daily question] Luogu p1605 maze
7.18 - daily question - 408
Unity slider slider development
Custom type