C编程中的堆内存 [英] Heap Memory in C Programming

查看:60
本文介绍了C编程中的堆内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是堆内存?

每当调用malloc时,就会从称为堆的东西中分配内存.堆到底在哪里.我知道主存储器中的程序分为存在程序语句的指令段,存储全局数据的数据段和存储局部变量和相应功能参数的堆栈段.现在,堆呢?

Whenever a call to malloc is made, memory is assigned from something called as heap. Where exactly is heap. I know that a program in main memory is divided into instruction segment where program statements are presents, Data segment where global data resides and stack segment where local variables and corresponding function parameters are stored. Now, what about heap?

推荐答案

堆是进程地址空间的一部分.堆可以增长或收缩;您可以通过调用brk(2)sbrk(2)对其进行操作.实际上,这就是malloc(3)的作用.

The heap is part of your process's address space. The heap can be grown or shrunk; you manipulate it by calling brk(2) or sbrk(2). This is in fact what malloc(3) does.

从堆分配比在栈上分配内存更方便,因为它在调用例程返回后仍然存在.因此,您可以调用一个例程,例如funcA(),以分配一堆内存并将其填充一些东西. funcA()返回后,该内存将仍然有效.如果funcA()在堆栈上分配一个本地数组,那么当funcA()返回时,堆栈上的数组就消失了.

Allocating from the heap is more convenient than allocating memory on the stack because it persists after the calling routine returns; thus, you can call a routine, say funcA(), to allocate a bunch of memory and fill it with something; that memory will still be valid after funcA() returns. If funcA() allocates a local array (on the stack) then when funcA() returns, the on-stack array is gone.

使用堆的一个缺点是,如果您忘记释放分配给堆的内存,则可能会耗尽它.无法释放堆分配的内存(例如,无法从malloc()获得free()内存)有时称为内存泄漏.

A drawback of using the heap is that if you forget to release heap-allocated memory, you may exhaust it. The failure to release heap-allocated memory (e.g., failing to free() memory gotten from malloc()) is sometimes called a memory leak.

与仅在堆栈上分配本地数组/结构/任何内容相比,堆的另一个不错的功能是,您将获得一个返回值,说明分配是否成功;如果您尝试在堆栈上分配一个本地数组而用尽,则不会收到错误代码.通常,您的线程只会被中止.

Another nice feature of the heap, vs. just allocating a local array/struct/whatever on the stack, is that you get a return value saying whether your allocation succeeded; if you try to allocate a local array on the stack and you run out, you don't get an error code; typically your thread will simply be aborted.

这篇关于C编程中的堆内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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