当前位置:网站首页>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;
}
边栏推荐
- Unity image control and rawimage
- ES6 modularization
- Chip sold at sand price: Lei Jun's dream was "ruined" by this company
- Document the use of anti shake in packaged components and projects
- unresolved external symbol [email protected] resolvent
- Game partner topic: the cooperation between breederdao and monkeyleague kicked off
- Musk responded whether he would upload his brain to the cloud: already did it!
- Synchronization primitive: lock
- Specificity and five applications of Worthington alcohol dehydrogenase
- Method properties of ASP adodb.stream object
猜你喜欢

Join MotoGP Monster Energy British Grand Prix!

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

VC hesitates to invest in Henan

Introduction to thread pool

Harbor installation

How to empty localstorage before closing a page

Worthington cytochrome c digestion study carboxypeptidase B scheme

Password input box and coupon and custom soft keyboard
![[27. Expression evaluation (infix expression)]](/img/af/cf3c4a441232caeea9f9927ebdf87b.png)
[27. Expression evaluation (infix expression)]

Green low-carbon Tianyi cloud, a new engine of digital economy!
随机推荐
Young people who lost the IPO
Latest information of 2022 cloud computing skills competition
Chapter IV drive subsystem development
Unity3d calls between different script functions or parameters
Pychart exits pytest mode (run pytest in mode)
How to obtain workers' coats and helmets in stray? How to obtain workers' helmets
Visual studio code installation package download slow & Installation & environment configuration & new one-stop explanation
Google Earth engine - 1980 present global pressure, temperature, wind and other data sets
Three possible scenarios for SAP Spartacus server-side rendering
Call camera photo album / upload / scan code in uniapp
Take C language from 0 to 1 - program structure and use examples
Cloud native platform, let edge applications play out!
What does it operation and maintenance management mean? How to establish an effective IT operation and maintenance management system?
Pytorch structure reparameterization repvggblock
Latex notes
How SAP Spartacus redefines login component
ASP rs.open SQL, Conn, what does 3, 1 stand for in 3,1?
unresolved external symbol [email protected] resolvent
How to create an index
2022/7/18-7/19