Skip to Content
LINUX系統程式設計 第二版
book

LINUX系統程式設計 第二版

by Robert Love
December 2013
Intermediate to advanced
496 pages
8h 57m
Chinese
GoTop Information, Inc.
Content preview from LINUX系統程式設計 第二版
338
|
第九章
system bytes = 3216519168
in use bytes = 3202567912
max mmap regions = 65536
max mmap bytes = 2350579712
基於堆疊的分配
目前我們已探討過的動態記憶體分配機制,都是使用堆積或記憶體映射來取得動態記
憶體。我們的預期也應該是這樣,因為堆積與記憶體映射本質上就是動態決定的。堆
疊(stack)是程式的位址空間中另一個常見的資料結構,用於存放程式的
自動變數
automatic variables
)。
然而,沒有理由說,一個程式設計者無法為動態記憶體分配使用堆疊。只要分配的結果
不會造成堆疊溢位(overflow),此類做法應該很容易,而且應該可以執行得相當好。要
從堆疊進行動態記憶體分配,可以使用
alloca()
系統呼叫:
#include <alloca.h>
void * alloca (size_t size);
執行成功時,
alloca()
會傳回一個指標,指向
size
個位元組的記憶體(空間)。此記憶
體(空間)位於堆疊之上,而且進行調用的函式返回時會自動釋出。有些實作會在執行
失敗時傳回
NULL
,但是多數的
alloca()
實作不會失敗,或者無法回報失敗的情況。失敗
的原因只可能是堆疊溢位。
用法如同
malloc()
,然而你不需要(的確,不必)釋出所分配的記憶體。下面的例子是
一個函式,此函式會在系統的組態目錄(可能是
/etc
,不過如果要移植到其他系統最好
在編譯時期決定)中開啟所指定的檔案。此函式會分配一個新的緩衝區,把系統組態目 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

AGILE學習手冊 | SCRUM、XP、精實和看板方法

AGILE學習手冊 | SCRUM、XP、精實和看板方法

Andrew Stellman, Jennifer Greene
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
算法技术手册(原书第2 版)

算法技术手册(原书第2 版)

George T.Heineman, Gary Pollice, Stanley Selkow

Publisher Resources

ISBN: 9789862769812