当前位置:网站首页>[C language] dynamic memory management, flexible array

[C language] dynamic memory management, flexible array

2022-07-25 09:16:00 Jiang Lingyu's daily account


One 、malloc

Two 、free

3、 ... and 、calloc

Four 、realloc

1、realloc Situation during capacity expansion :

2、realloc Can also be realized malloc function

5、 ... and 、 Common errors in using dynamic memory

1、free Null pointer

2、 Cross border access to dynamically opened space

3、 For non dynamic development content free

4、 only free Part of dynamic development space

5、 Multiple times for the same block of memory free

6、 Dynamic memory space forgot to release ( Memory leak )

6、 ... and 、 Flexible array

1、 Concept of flexible array

2、 The characteristics of flexible arrays

3、 Usage scenarios of flexible arrays

4、 Advantages of flexible arrays


One 、malloc

This function requests a continuous space from the heap , And return the address of this memory .

int main()
{
	int* p = (int*)malloc(40);
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
        return 1;
	}
	free(p);
	p = NULL;
	return 0;
}

If the development fails , Returns a NULL The pointer , therefore malloc The return value of must be checked .

If parameters size by 0,malloc The standard is undefined , Depends on the compiler .

Two 、free

free Function is used to release memory opened dynamically .free The pointer to must be the starting address of the dynamic memory space .

If parameters ptr The pointed space is not opened dynamically , that free The behavior of a function is undefined .

If parameters ptr yes NULL The pointer , Then the function does nothing .

3、 ... and 、calloc

num: The number of elements to be dynamically developed

size: The size of each element

calloc=malloc+memset

calloc and malloc The difference is calloc The space opened by dynamic memory will be initialized to 0

Four 、realloc

ptr: The original address that needs to be expanded

size: Total size after expansion

1、realloc Situation during capacity expansion :

1、 There is enough space in the rear when expanding , Will continue to expand in the rear , Return to the original address

2、 The rear space has been used when expanding , It will be expanded in a new area , And copy the original data to the new area ,free The memory pointed to by the original address , And return the address of the memory block .

3、 The space is insufficient , Can't expand , Return null pointer

2、realloc Can also be realized malloc function

int main()
{
	int* p = (int*)realloc(NULL, 40);
	return 0;
}

realloc When malloc When using , Pass the null pointer to the first parameter .

5、 ... and 、 Common errors in using dynamic memory

1、free Null pointer

void text()
{
	int* p = (int*)realloc(NULL, 40);
	if (p == NULL)// Judge p Null pointer or not 
	{
		return;
	}
	*p = 20;
}

If you open up space , No judgment pointer p Whether it is a null pointer , If dynamic memory development fails , that *p Will dereference null pointer .

2、 Cross border access to dynamically opened space

void text()
{
	int* p = (int*)realloc(NULL, 40);
	int* m = p;
	if (p == NULL)
	{
		return;
	}
	for (int i = 0; i <= 10; i++)
	{
		p[i] = i;// Transboundary 
		p++;
	}
}

3、 For non dynamic development content free

void text()
{
	int arr[] = {1,2,3};
	int* p = arr;
	free(p);// It is not allowed to conduct free
}

4、 only free Part of dynamic development space

void text()
{
	int* p = (int*)malloc(40);
	p++;
	free(p);//p No longer point to the starting position of dynamic opening space 
}

When actually writing code, you still have to pay more attention to this situation , The pointer p It is no longer the initial position in the process of use ,free(p) It will break down .

5、 Multiple times for the same block of memory free

void text()
{
	int* p = (int*)realloc(NULL, 40);
	free(p);
	//p = NULL;

	free(p);
}

free(p) After that, the p Set to null pointer , Even if the p Many times free Also no problem .

6、 Dynamic memory space forgot to release ( Memory leak )

void text()
{
	int* p = (int*)realloc(NULL, 40);
	int a = 0;
	scanf("%d", &a);
	if (a == 5)
		return;
	free(p);
	p = NULL;
}

When the function terminates in advance , There is no chance to go to free, May cause memory leaks

Another possibility is to call the function of dynamically opening up memory , The user is not doing it externally free

6、 ... and 、 Flexible array

1、 Concept of flexible array

C99 in , The last member variable in the structure can be an array of unknown size

struct S
{
	int a;
	int arr[0];// there arr[0] Represents an array of unknown size 
};
// Or as follows :
struct S
{
	int a;
	int arr[];
};

2、 The characteristics of flexible arrays

A flexible array member in a structure must be preceded by at least one other member .

sizeof The size of the structure returned does not include the memory of the flexible array .

Structures that contain flexible array members use malloc () Function to dynamically allocate memory , And the allocated memory should be larger than the size of the structure , To fit the expected size of the flexible array .

3、 Usage scenarios of flexible arrays

scene : Open all member variables in the structure in the heap

Use flexible arrays :

struct S
{
	int a;
	int arr[0];
};
int main()
{
	struct S s;
	struct S* ps = &s;
	ps = (struct S*)realloc(NULL,sizeof(s) + 40);// Opening up space for the first time , Pass on NULL
	if (ps == NULL)
	{
		exit(-1);
	}
	free(ps);
	ps = NULL;
	return 0;
}

Pay attention to realloc The first parameter passed in is NULL instead of &s, Pass in &s It will break down , Because this is the first dynamic memory development , Here comes NULL It is equivalent to using malloc

After completing the development s The storage in memory is shown in the figure below :

Use regular structures :

struct S
{
	int a;
	int* parr;
};
int main()
{
	struct S* p = (struct S*)malloc(sizeof(struct S));// Dynamically open up space for the structure 
	if (p == NULL)
	{
		exit(-1);
	}
	int* tmp= (int*)malloc(sizeof(int) * 2);// Dynamically open up a space in the stack area 
	if (tmp == NULL)
	{
		exit(-1);
	}
	p->parr = tmp;
	free(p->parr);// On release , Need to release first p->parr Point to space 
	p->parr = NULL;
	free(p);// Then the structure pointer p The space pointed to is released 
	p = NULL;
	return 0;
}

After completing the development s The storage in memory is shown in the figure below :

4、 Advantages of flexible arrays

1、 Under the above conditions , Use flexible arrays to facilitate dynamic memory release . If our code is in a function for others , You do a secondary memory allocation in it , And return the whole structure to the user . The user calls free You can release the structure , But the user doesn't know that the members in the structure also need free, May cause memory leaks . therefore , If we allocate the memory of the structure and its members at one time , And return a structure pointer to the user , The user does it once free You can free up all the memory .

2、 Continuous memory is good for improving access speed , It also helps reduce memory fragmentation .

原网站

版权声明
本文为[Jiang Lingyu's daily account]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/201/202207191246140695.html