当前位置:网站首页>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;
}
边栏推荐
- Boutique solution | Haitai cloud password application service solution to create secure and compliant Cloud Applications
- Sort out some scattered knowledge points by yourself
- MySQL series | log module
- Six stones Management: the process is only convenient to shirk responsibility, but not helpful to solve problems
- Antdb database products were selected into the global database industry map (2022) of the China Academy of communications and communications
- Point to point copy and paste of web pages
- record
- [summer daily question] Luogu p1706 full ranking question
- 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
- Chapter IV drive subsystem development
猜你喜欢

7.19 - daily question - 408
![Detailed explanation of zero length array in C language (1) [information at the end of the article]](/img/89/1f01e24ce52b2d459f26397cd8527f.png)
Detailed explanation of zero length array in C language (1) [information at the end of the article]

Pursue and kill "wallet Assassin" all over the network
![[27. Expression evaluation (infix expression)]](/img/af/cf3c4a441232caeea9f9927ebdf87b.png)
[27. Expression evaluation (infix expression)]

Chip sold at sand price: Lei Jun's dream was "ruined" by this company

Musk responded whether he would upload his brain to the cloud: already did it!

Turn: emotional internal friction is the biggest source of inefficiency in your life

Pads copper laying

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

Pytorch structure reparameterization repvggblock
随机推荐
Chip sold at sand price: Lei Jun's dream was "ruined" by this company
The position of the nth occurrence of MySQL in the string
Plug ins QRcode and ityped
Detailed explanation of zero length array in C language (1) [information at the end of the article]
Introduction to thread pool
Method properties of ASP adodb.stream object
Pads copper laying
How SAP Spartacus redefines login component
[summer daily question] Luogu p1706 full ranking question
How to empty localstorage before closing a page
Construction of Seata multilingual system
Summary of the most complete MySQL data types in history (Part 2)
Take C language from 0 to 1 - program structure and use examples
[C + + primer notes] Chapter 8 IO Library
Example analysis of enum data type in MySQL
Harbor installation
Vegetable greenhouses turned into smart factories! Baidu AI Cloud helps Shouguang, Shandong build a new benchmark for smart agriculture
Chapter III kernel development
The introduction of 23 Filipino doctors for 18million was a hot topic, and the school teacher responded: expedient
ASP rs.open SQL, Conn, what does 3, 1 stand for in 3,1?