C 最佳实践,堆栈与堆分配 [英] C best practices, stack vs heap allocation

查看:22
本文介绍了C 最佳实践,堆栈与堆分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在使用 c 并且发现我真的不喜欢处理内存管理,或者至少我认为如果我 malloc 一个指针我必须释放它,即使它是最微不足道的事情.这导致我尽可能多地在堆栈上分配并使用 &得到它的位置.甚至制作单独的 int 和 inptr 变量(我在宏中使用 & 运算符时遇到了一些左值问题).

I have been using c a lot more recently and finding that I really don't like dealing with memory management, or at least the idea that if I malloc a pointer I have to release it even if its the most trivial thing. This has lead me to allocating as much as possible on the stack and using & to get its location. Even making separate int and inptr variables(I've had some lvalue problem with & operator in macros).

我还没有找到很多我必须处理在分配数据的地方向上(上方/下方)传递数据的地方.同时,我需要大量的早期回报(我宁愿避免 goto).一般的c意见是什么?是否有任何明显的迹象表明我应该在特定情况下使用一种或另一种.

I haven't find many places where I have had to deal with passing data up (above/below) where it was allocated. At the same time I need a decent amount of early returns(and I would rather avoid gotos). What is the general c opinion say? Are there any obvious signs I should use one or another in a particular case.

附:让我有点担心的一件事是,由于对 malloc 使用了错误的 sizeof,我最近遇到了内存损坏问题,我没有立即注意到它,因为在那之后我的大部分代码路径都没有使用堆.您认为这种隐藏腐败的问题可能有多大?

P.S. One thing that made me worry a bit was that I recently got a memory corruption problem due to using the wrong sizeof for malloc and I didn't notice it right away since most of my code paths directly after that point didn't utilise the heap. How big of a problem do you think this sort of corruption hiding might be?

推荐答案

你应该使用 malloc 如果:

  1. 您将指向非static const 数据的指针向上传递到调用堆栈,或者
  2. 您正在分配变量或只是大量数据(否则您有堆栈溢出的风险).
  1. You're passing pointers to non-static const data up the call stack, or
  2. you're allocating variable or simply large amounts of data (else you risk stack overflow).

在其他情况下,堆栈分配应该没问题.

In other cases, stack allocation should be fine.

这篇关于C 最佳实践,堆栈与堆分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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