正确使用malloc [英] Proper use of malloc

查看:104
本文介绍了正确使用malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过的这本书中的一章着重介绍了使用malloc linux函数进行内存管理分配空间.

A chapter out of the book I have been reading has focused on memory management allocating space using malloc linux functions.

在我读这篇文章之前,我会在不分配空间的情况下制作相对较小的程序.

Before I read this I would make relatively small programs without allocating space.

对于内存占用量保持在50MB以下的应用程序不做任何内存分配方式是否可以接受?不这样做的后果是什么?

Is it acceptable to not do anything in the way of memory allocation for applications whose memory footprint remains under 50MB? What are the repercussions of not doing so?

推荐答案

如果不为小型应用程序使用malloc,则可能不需要使用任何堆空间.小小的实用程序或玩具程序通常不会.当您应该使用堆时可能遇到的错误是:

If you can do without malloc for small applications, you're probably just not needing to use any heap space. Little utility programs or toy programs often don't. The things you might be doing wrong though to get by when you should be using the heap are:

  1. 数组.如果发现自己只是为了确保所有内容都适合而分配大型数组,那么您可能应该使用malloc.至少要处理所有溢出的错误情况,以检查它们是否确实足够大.使用动态分配的阵列,如果发现需要更多空间,则可以即时制作更大的阵列.

  1. Arrays. If you find yourself allocating large arrays 'just to make sure everything fits' then you should perhaps be using malloc. At the least, handle the error condition that everything overflows to check they really are big enough. With dynamically allocated arrays, you can make bigger ones on the fly if you find you need more space.

执行过多的递归. C得益于有时可以将递归平坦化为数组循环,因为与函数语言不同,它无法正确优化事物.如果您通过调用很多函数来创建存储空间,那将非常危险(程序有一天可能会崩溃).

Doing too much recursion. C benefits from flattening out recursion sometimes into loops over arrays, because unlike function languages it can't optimise things properly. If you are getting your storage space by calling function lots to create it, that's pretty dangerous (the program might crash on you one day).

使用对象(结构,类)的静态池.也许您有一个环形缓冲区,其中可能有15个对象,并且您已经静态分配了它们,因为您知道缓冲区永远不会超过15个条目.可以,但是可以通过添加更多使用malloc创建的结构来允许缓冲区增长更多.

Using static pools of objects (structs, classes). Perhaps you have a ring buffer, and 15 objects that could be in it, and you have them statically allocated because you know that your buffer will never have more than 15 entries. That's kind of OK, but allowing the buffer to grow more by adding in more structs, created with malloc, might be nice.

可能有更多的情况,不需要malloc的程序可以通过添加它而受益.

Probably plenty more situations where programmes which don't need malloc could benefit from having it added.

这篇关于正确使用malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆