C Dynamic memory management in language mainly depends on four dynamic memory functions .

Four functions :malloc,calloc,realloc,free. All four functions require #inlude<stdlib.h>.

1. Why is there dynamic memory management ?

If you create an array using the usual , Variable and other methods to apply for space , These spaces are fixed in size . If it is necessary to increase / The actual demand for reduced space often fails to meet the requirements . So it is more convenient to derive , Efficient ( Space and time utilization ) Dynamic memory management mode .

2. Area in memory

Memory is divided into many areas , The space of each region has different characteristics .

Here we mainly analyze Stack area , Heap area and static area .

In stack area , It mainly stores the formal parameters of local variables and functions .

In heap area , It mainly stores functions for dynamic memory allocation (malloc,calloc,realloc,free) Space of action .

In static area , It mainly stores global variables and static variables .

function :

malloc:void* malloc(size_t size)

size_t Represents an unsigned integer .malloc Open up a size Bytes of contiguous free space , And return the first address of this space , If there is insufficient space in the stack area , Then return NULL.

be careful : The type of return address is void*, To use this address, create variable inheritance and force type conversion .

if size by 0, be malloc Unknown behavior of , Determined and interpreted by the compiler .

give an example :

int* p=(int*)malloc(10*sizeof(int));// Open up ten integer spaces and assign the first address to the p

if(p==NULL)

{

perror("malloc");// Print current error message

return 1;// End program

}

after p According to its own type (int*) Access this space .

And after the visit free(p); p=NULL; 
 free( First address of dynamic opening memory ) This dynamically developed space can be released , After release p Equivalent to wild pointer ( The address pointed to is meaningless ), Therefore, it is necessary to assign NULL to p prevent p Possible changes to the space of useful data . If the dynamic requested memory space is not released , This memory will always occupy the space in the heap , Cause memory leak .

calloc:void* calloc(size_t num,size_t size)

calloc Open up in the stack area num individual size Bytes of contiguous free space . And malloc Different ,calloc Will initialize the open space to 0( The data of each bit is 0). Return if space creation fails NULL.

give an example :int* p=(int*)calloc(10,sizeof(int));// Ten integer spaces are opened and initialized to 0

realloc function : void* realloc(void* p,size_t size)

Slave address p Start backwardly size Bytes of contiguous free space .

c-realloc During the operation, the old space is released and the new space is allocated and returned .

use realloc There are two situations :

1. If the pointer of the previously dynamically applied space p Later size Bytes of space , Directly at p Then open up the remaining space .

2. If the pointer of the previously dynamically applied space p Not since size Bytes of space , Just reapply in the heap size Bytes of space , Then return to the first address of this space .

If the space application fails, a NULL. The content in the open space is also unknown .

Let's take a look at common dynamic memory management errors :

1. yes NULL Perform dereference - operation failed

resolvent : yes malloc To perform an emptying operation , Just use if judge malloc Whether the return value is NULL And carry out corresponding treatment

2. Cross border access to dynamic open space

resolvent : Check the code yourself

3. For non dynamic development space free operation — here free No effect and error

resolvent : Check code

4. use free Part of the dynamically developed memory is released ( Memory should be freed completely )

Possible causes : The pointer value used to apply for space is changed at the beginning , Code to be checked

5. Release the same memory multiple times

here free No effect —— Or it may affect the normal code , Need to check .

6. Dynamic development memory forgetting to release ( Memory leak )

Possible causes : After applying for space with a local variable such as a function, the variable is deleted , This space cannot be freed .

Training topics 1:

void Fetmemory(char*p)

{

p=(char *)malloc(100);

}

void test(void)

{

char * str=NULL;

Getmemory(str);

strcpy(str,"helloworld");

printf(str);

}

result : Nothing to print .

First, explain printf(str); What do you mean? :printf Function receives an address at runtime , Then print characters from this address , encounter '\n','\0' Stop printing when ( But the effect of escape will be expressed ). therefore printf(str) Is correct , same char
s[]="asdfg"; printf(s); char* p="asd";printf(p) All of them are right .

General ,printf Controls are used to output content , The operation mechanism is different when the address is received .

Will not print hello
world Reason for :str Is a pointer , The contents stored inside are NULL. When transferring parameters ,p Not at all str,p just str A temporary copy of ,p The content of NULL, after malloc after p The content of becomes the first address of a space , but str Content or NULL( that is str There is no memory that has been requested to be used ), bring strcpy And printf invalid . and p Memory of has not been freed , Cause memory leak .

Correct writing :

void getmemory(char** p)

{

*p=(char*)malloc(100);// here *p Delegate pointer str,str Given an address, you can operate

}

void test(void)

{

char* str=NULL;

getmemory(&str);// take str Send me your address , Through dereference, you can accurately str assignment

strcpy(str,"helloworld");

printf(str);

free(str);

str=NULL;

}// of course test Function needs to be in main Used in .

subject 2:

char* getmemory(void)

{

char p[]="helloworld";

return p;

}

void test(void)

{

char* str=NULL;

str=getmemory();

printf(str);

}

result : Do not print hello world, Print out random values .

reason : although str Received the address returned by the function and pointed to that space , But this is after the function call , The array space created in the function no longer has access rights ( Has been released )( even if str Point to the first address of that space ), Therefore, random values will appear if it is forcibly used , here str Is a wild pointer ( Pointing space not initialized , Or no access to the space )

This problem is generally called the problem of returning stack space address , Addresses in stack space should not be returned easily , This space can easily be recycled permission ( Stack space is easily freed ). Because there are many functions in the program , Content in this space can easily be changed to other values .

  Areas in memory .

Flexible array : Last element in structure ( member ) Arrays of unknown size are allowed .( When creating an array, do not specify a space size or specify a space size of 0)

struct s1

{

int num;

double d;

int arr[];

}

struct s2

{

int num;

double d;

int arr[0]

}

Both of these two flexible array creation methods are valid .

Characteristics of flexible array :

1. At least one member precedes the flexible array member in the structure

2.sizeof Do not calculate when calculating the size of the structure ( include ) Size of flexible array members

3. To main When using structure pointer to open up space in , In addition to opening up sizeof( Structure type ) Space for , It also needs to open up the space occupied by the expected flexible array .

give an example :

struct s3* ps=(struct s3*)malloc(sizeof(struct s3)+40);//40 Expected size for flexible array

for(i=0;i<10;i++)

{

ps->arr[i]=i;// The use of flexible arrays is the same as that of ordinary arrays .

}

be careful : There is another “ Flexible array ” Implementation of : Replace the flexible array with a pointer of the corresponding type , stay main After applying for the space of the structure in, use this pointer to “ Flexible array ” Apply for space . But please note : The space requested with a flexible array is continuous , The space requested with a pointer is not necessarily continuous . The method of using a pointer when freeing memory also needs to be used free Free up two spaces . But both of these methods can achieve the desired effect .

as :

struct s4* p=(struct s4)malloc(sizeof(struct s4));

p->arr=(int*)malloc(10*sizeof(int));// hypothesis arr by int* type

On release :free(p->arr); free(p);// Free up space for two requests

Advantages of flexible array :

1. Easy to free memory

2. If the space to be accessed is continuous in memory , Faster access , Because all programs have to be extracted into registers and then taken out after running , Flexible array improves access speed . The unused space is called memory fragmentation , Use flexible arrays to reduce memory fragmentation .

Technology
©2019-2020 Toolsou All rights reserved,
【C++ Must see for entry 】C++ from 0 reach 1 Introductory programming axios Interceptor packaging and use Spring Boot Interview must ask : Automatic configuration principle VMware 16 install centos 7 Detailed tutorial C Language data structure - Sequence table delete duplicates V2.0.0 The 12th Blue Bridge Cup c++b Group personal problem solving On sending data from serial port single chip microcomputer to upper computer centos7 install RabbitMqjava Polymorphic array of opencv-python Fourier transform and inverse transform