內(nèi)存管理 #1

進(jìn)程地址空間

Pages and Paging

bits => bytes => words => pages
page是MMU(memory management unit)的最小地址單元
虛擬地址空間被分割成pages。
機(jī)器架構(gòu)決定了page的size状原。一般來(lái)說(shuō)32位的系統(tǒng)是4KB艾恼,64位的系統(tǒng)是8KB别垮。

Sharing and copy-on-write(COW)

Memory Regions

  • text segment: code, string literals, constant variables, and other read-only data.
  • stack: process's execution stack.
  • data segment or heap:
  • bss segment: uninitialized global variables

分配動(dòng)態(tài)內(nèi)存

任何內(nèi)存管理系統(tǒng)的foundation是分配搅幅,使用考抄,和到最后的返還dynamic memory展姐。

// classic C interface for obtaining dynamic memory
#include <stdlib.h>
void *malloc(size_t size);
char *p;
/* give me 2 KB!*/
p = malloc(2048);
if(!p)
    perror("malloc");
struct treasure_map *map;
map = malloc(sizeof(struct treasure_map));
if(!map)
    perror("malloc");
//c++ need to typecast malloc()'s return
char *name;
/* allocate 512 bytes*/
name = (char *)malloc(512);
if(!name)
    perror("malloc");
//wrapper of malloc
// like malloc(), but terminates on failure
void *xmalloc(size_t size)
{
    void *p;
    p = malloc(size);
    if(!p){
          perror("xmalloc");
          exit(EXIT_FAILURE);  
    }
    return p;
}

Allocating Arrays

#include <stdlib.h>
void *calloc(size_t nr, size_t size);
int *x, *y;
x = malloc(50 * sizeof(int));
if(!x){
      perror("malloc")l
      return -1;
}
y = calloc(50, sizeof(int));
if(!y){
    perror("calloc");
    return -1;
}

雖然看上去是一樣的,但上面兩個(gè)的行為是不同的犁柜。malloc不保證分配內(nèi)存的內(nèi)容是什么洲鸠,calloc會(huì)把分配到的內(nèi)存走初始化位0。

/* works identically to malloc(), but memory is zeroed*/
void *malloc0(size_t size)
{
    return calloc(1, size);
}
/* like malloc(), but zeros memory and terminated on failure*/
void *xmalloc0(size_t size)
{
    void *p;
    p = calloc(1, size);
    if(!p){
        perror("xmalloc0");
        exit(EXIT_FAILURE);
    }
    return p;
}

Resizing Allocations

#include <stdlib.h>
void *realloc(void *ptr, size_t size);

If size is 0, 效果和free()是一樣的馋缅。

struct map *p;
/* allocate memory for two map structures*/
p = calloc(2, sizeof(struct map));
if(!p){
    perror("calloc");
    return -1;
}
/* use p[0] and p[1]*/
struct map *r;
/* we now need memory for only one map*/
r = realloc(p, sizeof(struct map));
if(!r){
    /*note that 'p' is still valid!*/
    perror("realloc");
    return -1;
}
/*use 'r'*/
free(r);

如果調(diào)用返回失敗扒腕,則p未被觸及,因此仍然有效萤悴。我們可以繼續(xù)使用它瘾腰,并最終需要釋放它。相反稚疹,如果調(diào)用成功居灯,則忽略p祭务,而使用r代替内狗。

Freeing Dynamic Memory

#include <stdlib.h>
void free(void *prt);

Alignment

在編寫(xiě)可移植代碼時(shí)怪嫌,程序員必須小心避免違反對(duì)齊要求。

Allocating alignment memory

在大多數(shù)情況下柳沙,編譯器和C庫(kù)透明地處理對(duì)齊參數(shù).POSIX命令通過(guò)malloc()岩灭、calloc()和realloc()返回的內(nèi)存對(duì)齊以供任何一種標(biāo)準(zhǔn)的C類(lèi)型使用。在linux上赂鲤,這些函數(shù)總是返回在32位系統(tǒng)上沿著8字節(jié)邊界對(duì)齊的內(nèi)存噪径,在64位系統(tǒng)上返回沿16字節(jié)邊界對(duì)齊的內(nèi)存。

/* one or the other -- either suffices */
#define _XOPEN_SOURCE 600
#define _GNU_SOURCE
#include <stdlib.h>
int posix_memalign (void **memptr, size_t alignment, size_t size);

成功的調(diào)用將返回0数初,并且分配size大小并且按照alignment大小對(duì)齊的動(dòng)態(tài)內(nèi)存找爱。
失敗的話,會(huì)設(shè)置errno泡孩。

char *buf;
int ret;
/* allocate 1 KB along a 256-byte boundary */
ret = posix_memalign (&buf, 256, 1024);
if (ret) {
    fprintf (stderr, "posix_memalign: %s\n",
    strerror (ret));
    return ?1;
 }
/* use 'buf'... */
free (buf);

Other alignment concerns

Managing the Data Segment

堆中的動(dòng)態(tài)內(nèi)存分配從段的底部向上增長(zhǎng)车摄;棧從段的頂部向下擴(kuò)展到堆。
將兩者分開(kāi)的分界線稱(chēng)為斷點(diǎn)或斷點(diǎn)仑鸥。

#include <unistd.h>
int brk (void *end);
void * sbrk (intptr_t increment);

A call to brk() sets the break point (the end of the data segment) to the address specified by end. On success, it returns 0. On failure, it returns ?1 and sets errno to ENOMEM.
A call to sbrk() increments the end of the data segment by increment bytes, which may be a positive or negative delta. sbrk() returns the revised break point. Thus, an increment of 0 provides the current break point:

    printf ("The current break point is %p\n", sbrk (0));

Deliberately, both POSIX and the C standard define neither of these functions. Nearly all Unix systems, however, support one or both. Portable programs should stick to the standards-based interfaces.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末吮播,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子眼俊,更是在濱河造成了極大的恐慌意狠,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,695評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件疮胖,死亡現(xiàn)場(chǎng)離奇詭異环戈,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)澎灸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)谷市,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人击孩,你說(shuō)我怎么就攤上這事迫悠。” “怎么了巩梢?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,130評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵创泄,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我括蝠,道長(zhǎng)鞠抑,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,648評(píng)論 1 297
  • 正文 為了忘掉前任忌警,我火速辦了婚禮搁拙,結(jié)果婚禮上秒梳,老公的妹妹穿的比我還像新娘。我一直安慰自己箕速,他們只是感情好酪碘,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,655評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著盐茎,像睡著了一般兴垦。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上字柠,一...
    開(kāi)封第一講書(shū)人閱讀 52,268評(píng)論 1 309
  • 那天探越,我揣著相機(jī)與錄音,去河邊找鬼窑业。 笑死钦幔,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的常柄。 我是一名探鬼主播鲤氢,決...
    沈念sama閱讀 40,835評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼拐纱!你這毒婦竟也來(lái)了铜异?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,740評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤秸架,失蹤者是張志新(化名)和其女友劉穎揍庄,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體东抹,經(jīng)...
    沈念sama閱讀 46,286評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蚂子,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,375評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了缭黔。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片食茎。...
    茶點(diǎn)故事閱讀 40,505評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖馏谨,靈堂內(nèi)的尸體忽然破棺而出别渔,到底是詐尸還是另有隱情,我是刑警寧澤惧互,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布哎媚,位于F島的核電站,受9級(jí)特大地震影響喊儡,放射性物質(zhì)發(fā)生泄漏拨与。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,873評(píng)論 3 333
  • 文/蒙蒙 一艾猜、第九天 我趴在偏房一處隱蔽的房頂上張望买喧。 院中可真熱鬧捻悯,春花似錦、人聲如沸淤毛。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,357評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)钱床。三九已至荚斯,卻和暖如春埠居,著一層夾襖步出監(jiān)牢的瞬間查牌,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,466評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工滥壕, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留纸颜,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,921評(píng)論 3 376
  • 正文 我出身青樓绎橘,卻偏偏與公主長(zhǎng)得像胁孙,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子称鳞,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,515評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容