嵌入式基础知识:内存的动态分配

动态分配出来空间在堆里,如果动态分配出来的空间使用完成后不回收,只会在所属的进程退出,系统才会回收。如果进程一直不退,动态分配越来越多的空间,会引起系统可用内存不足,这就是内存泄漏。


注意:分配在堆里的空间,所在函数执行结束也不会自动回收分配在堆里的空间(会自动回收栈里分配的空间).只有调用回收函数或者进程退出才可以回收堆里分配的空间。


检查C/c++程序执行时是否有内存泄漏,可用命令:<valgrind 可执行文件>



1

2 #include<iostream>

3 #include<stdlib.h>

4

5 int main(void)

6 {

7 int *p;

8

9 p = (int*)malloc(sizeof(int)); // 只有动态分配,没有回收

10 return 0;

11 }


编译后,用命令检查:

[root@localhost05new_delete]# valgrind ./a.out

==7001== Memcheck, amemory error detector

==7001== Copyright(C) 2002-2013, and GNU GPL'd, by Julian Seward et al.

==7001== UsingValgrind-3.10.0 and LibVEX; rerun with -h for copyright info

==7001== Command:./a.out

==7001==

==7001==

==7001== HEAPSUMMARY:

==7001== in useat exit: 4 bytes in 1 blocks

==7001== totalheap usage: 1 allocs, 0 frees, 4 bytes allocated

==7001==

==7001== LEAKSUMMARY:

==7001== definitely lost: 4 bytes in 1 blocks

==7001== indirectly lost: 0 bytes in 0 blocks

==7001== possibly lost: 0 bytes in 0 blocks

==7001== stillreachable: 0 bytes in 0 blocks

==7001== suppressed: 0 bytes in 0 blocks

==7001== Rerun with--leak-check=full to see details of leaked memory

==7001==

==7001== For countsof detected and suppressed errors, rerun with: -v

==7001== ERRORSUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)


在代码里加上回收空间的处理

1

2 #include<iostream>

3 #include<stdlib.h>

4

5 int main(void)

6 {

7 int *p;

8

9 p = (int*)malloc(sizeof(int));

10

11 free(p);

12 return 0;

13 }


再编译,检查:

[root@localhost05new_delete]# valgrind ./a.out

==7519== Memcheck, amemory error detector

==7519== Copyright(C) 2002-2013, and GNU GPL'd, by Julian Seward et al.

==7519== UsingValgrind-3.10.0 and LibVEX; rerun with -h for copyright info

==7519== Command:./a.out

==7519==

==7519==

==7519== HEAPSUMMARY:

==7519== in useat exit: 0 bytes in 0 blocks

==7519== totalheap usage: 1 allocs, 1 frees, 4 bytes allocated

==7519==

==7519== All heapblocks were freed -- no leaks are possible

==7519==

==7519== For countsof detected and suppressed errors, rerun with: -v

==7519== ERRORSUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)




C语言里用malloc函数动态分配空间,用free函数回收空间。

C++语言里用new关键字动态分配空间,用delete关键字回收空间.


C++:

int *p, *p2 ;


//动态分配一个int型的变量空间

p = new int; // new 后面直接写类型

//动态分配一个int型的数组空间,数组元素个数为5

p2 = new int [5];



//回收空间

delete p;

delete [] p2; //回收连续的空间时,<delete>后需加上”[]”符号


注意:在c++里也是可以c里的malloc分配空间,free回收空间.但是建议还是改成使用C++newdelete,因为它们有比malloc/free更多的功能.

new 会触发类的构造函数,delete会触发类的析构函数.malloc/free是无法触发这些函数的.




c++里通常会用到一个词“对象”

对象其实就是分配出来的某种类型的具体空间.

如有类型,MyCls;

MyCls a; //a 就是对象

MyCls *a = newMyCls; // a指向对象.“new MyCls”创建出对象,并把地址给指针变量a存放起来.

建议尽量使用后面这种方法创建对象,这样比较安全.


本文由广州尚观科技发布,广州尚观科技,专业的嵌入式/Linux/Java大数据/python/UI培训机构。扫下方二维码关注我们,可获得免费精品视频一份。



猜你喜欢

转载自blog.csdn.net/gz_sgkj/article/details/80350195