CS50筆記4_指針Pointer

Hexadecimal (Base 16)

- 0 ~ 9 + A ~ F as equivalent to 10 ~ 15

- e.x. 1A = 1*16^1 + 10*16^0 = 26

- The maximum value with two digits in the hexadecimal system (15*16^1 + 15*16^0 = 255) is equivalent to the max value with 8 bits in binary. Each digit in the hexadecimal system with 16 values maps to 4 bits in binary, which makes it more convenient to store the address of memory.

- Prefix: "0x", for example: 0x00FFFF. It means nothing but to notify when start parsing.

- Application in the RGB color system:

? ? ? ? - conventionally use hexadecimal to describe the amount of color



Address

- &: get the address of variable x

- *: go to the address of variable x

printf( "%p\n", &x );? ? ? ? ? ? ? ? // print out the address

printf( "%i\n", *&x );? ? ? ? ? ? ? ? // look inside a particular memory address and print out the value there



Pointer (8 bytes)

- A type of variable which stores an address of other values

- A value that points to a location in memory, like an arrow

- Pointers allow us to actually pass the variable itself, not the copy.

- If we create a pointer but not set the value immediately, the value of this pointer should always be set to NULL. If we try to dereference a pointer with the NULL value, we may encounter a segfault as it points to nothing.

- In C, pointers refer to specific types of values

int n = 50;

int *p = &n;

printf( "%p\n", p);? ? ? ? ? ? ? ? // print out the address of variable n

int *px, *py, *pz;? ? ? ? ? ? ? ? // create multiple pointers in the same line

- There can be a pointer to character / boolean / integer ......

- Modern computer system has 64 bits to address the memory.



Strings

- In C, string, as a data type, actually does not exist.

- Recall string used to be considered as a contiguous array of characters, it is indeed defined as pointers in <cs50.h>, as an address to some characters in memory.

- Example:

? ? ? ? string s = "HI!";? ? ? ? ? ? ? ? //s[0] = 'H'; s[1] = 'I'; s[2] = '!'; s[3] = '\0';

? ? ? ? Let s be the pointer with the address of the first character s[0] based on their contiguous address. So this variable s stores the address of the first character of the string (0x123), and the rest of the characters are in an array back-to-back.

? ? ? ? The working principle of defining string is to start at the address in s (s[0]), reaching 1 character (1 byte) at a time from the memory, and ending when hit the null character.

char *s = "HI!";? ? ? ? ? ? ? ? // store the address of the first character and point to its location in memory



Pointer Arithmetic

char *s = "HI!";

printf( "%c\n", s[0]);? ? ? ? ? ? ? ? // || printf( "%c\n", *s);

printf( "%c\n", s[1]);? ? ? ? ? ? ? ? // ||? printf( "%c\n", *(s+1) );

printf( "%c\n", s[2]);? ? ? ? ? ? ? ? // ||? printf( "%c\n", *(s+2) );

- char *: store the address of "H" and name the variable s

- *s: go to the address stored in the variable s and print out the value there

- *(s+1): go to the location in memory with the address one byte higher (the next character), which is a syntactic sugar for s[1], equivalent in function but less readable.



Segmentation Fault (Segfault)

- Try to read or write the illegal memory location ( e.x. *(s+1000000) ), which will cause programs to crash.



Malloc

- Allocate some number of bytes in memory (blank memory, like garbage values) and pass in the numbers of memory marked for use (see COPY STRING for more details).

- This function will return NULL when the computer runs out of memory, and a NULL pointer is indeed a bogus address, or there is no address to point to. So always check whether malloc returns a null pointer in case of segfaults.?

Free

- Free the allocated memory before the main function returns

- The free function marks those allocated memories as usable again, values stored there remain as garbage values.



Garbage Value

- Unknown random values at some address in the memory from the previous running program. It doesn't make sense, as it is not given by any logic.

- When we call the free function, values stored at those used memories won't be erased or set back to zero. Instead, these remnants will be left alone for later reuse.

int main(void)

{

? ? ? ? int *x;

? ? ? ? int *y;

? ? ? ? x = malloc( sizeof( int ) );

? ? ? ? *x = 19;? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // go to the address x points to and set that location in memory to the value 19

? ? ? ? *y = 84;? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // garbage value

? ? ? ? // through we trying to put the value 84 at the address y points to, we never assign y a value

? ? ? ? // y looks like an address but indeed not a valid address

? ? ? ? // we may go to some unknown address when try to go to the garbage value in y as an address, which is likely to cause a segmentation fault (segfault)

}

- To see garbage values:

int main(void)

{

? ? ? ? int score[3];? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // int *score, allocate 3 bytes without putting values there

? ? ? ? for (int i = 0; i < 3; i++)

? ? ? ? {

? ? ? ? ? ? ? ? printf("%i\n", score[i]);? ? ? ? // see previous uninitialized values in the reused memory

? ? ? ? }

}

- Exception: global variables

? ? ? ? Global variables are constants outside the context of main and all other functions, and will conventionally initialize to zero or null.



Memory Layout

- Different types of data are stored and organized into different sections.

- Machine code(代碼): compiled binary codes, loaded into the top of memory

- Globals(靜態(tài) / 全局變量): global variables (see the exceptions above)

The following is a shared pool of memory.?

- Heap(堆):

? ? ? ? The empty area from where the malloc function can get free memory for programs to use. Once we call the malloc function, it starts to allocate memory from the top down (↓).

? ? ? ? - A pool where dynamically allocated memory comes from, with the access of pointers


All files live on the disk drive

(hard disk drive HDD or solid-state drive SSD), a permanent location that couldn't be modified in such storage space. Manipulation and use of data can only take place in the random access memory RAM, a much smaller place where all of the volatile data exists. Data in RAM will be destroyed when the computer battery died.

? ? ? ? Volatile data is any data that is stored in memory or exists in transit, that will be lost when the computer loses power or is turned off. Volatile data resides in registries, cache, and random access memory (RAM).

Memory is essentially a huge array of 8-bit wide bytes (such as 512MB, 1GB, 2GB, 4GB)


- Stack(棧):

? ? ? ? Stack is a sort of dynamic place that memory gets used and reused. It grows upwards (↑).?

? ? ? ? When we call a new function, a new frame is pushed onto the top of the stack and becomes the active frame. (swap then main at the bottom) There is always only one active frame. The new frame popped off of the stack when this function is completed, and the lower one turned to be the new active function on the top of the stack instead.?

? ? ? ? Used by local variables and functions in our programs as we are called, which will be auto-discarded(執(zhí)行完自動銷毀). Those functions don't physically disappear but become garbage values after execution, and the memory they were using is freed for the next function call. ( For dynamically-allocated memory, they won't automatically return to the system for later use, and such failure to return memory back to the system when we are finished with it could result in a memory leak. )

? ? ? ? Example (see Swap):

? ? ? ? ? ? ? ? ? ? ? ? ? ? Swap Function (on top of main with local variables a, b, temp)

? ? ? ? ? ? ? ? ? ? ? ? ? ? Main Function (at the very bottom of the stack with variables x, y)

- Typically there will be enough memory the heap and stack won't collide.

- heap overflow: call the malloc function for too much memory and pass the heap

- stack overflow: call too many functions without returning from them (like set height as 999,999,999 in the programs below). We will meet the segfault (segmentation fault) when running out of memory on the stack.

? ? ? ? Example: Recursion

? ? ? ? void draw(int h);

? ? ? ? int main(void)

? ? ? ? {

? ? ? ? ? ? ? ? int height = get_int( "Height: " );

? ? ? ? ? ? ? ? draw( height );

? ? ? ? }

? ? ? ? void draw(int h)

? ? ? ? {

? ? ? ? ? ? ? ? if (h == 0)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // base case

? ? ? ? ? ? ? ? ? ? ? ? return;

? ? ? ? ? ? ? ? for ( int i = 0; i < h; i++)

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? printf( "#" );

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? printf( "\n" );

? ? ? ? ? ? ? ? draw(h-1);

? ? ? ? }

// Output:

? ? ? ? ###

? ? ? ? ##

? ? ? ? #

- buffer overflow:

? ? ? ? buffer: a chunk of memory used to fit / retrieved by malloc

? ? ? ? ? ? ? ? Example: preloaded video clip before offline

? ? ? ? buffer overflow: go past of the end of the allocated chunk of memory when using the malloc function

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖榕吼,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡救斑,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進店門真屯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來脸候,“玉大人,你說我怎么就攤上這事绑蔫≡寺伲” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵晾匠,是天一觀的道長茶袒。 經(jīng)常有香客問我,道長凉馆,這世上最難降的妖魔是什么薪寓? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮澜共,結(jié)果婚禮上向叉,老公的妹妹穿的比我還像新娘。我一直安慰自己嗦董,他們只是感情好母谎,可當我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著京革,像睡著了一般奇唤。 火紅的嫁衣襯著肌膚如雪幸斥。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天咬扇,我揣著相機與錄音甲葬,去河邊找鬼。 笑死懈贺,一個胖子當著我的面吹牛经窖,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播梭灿,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼画侣,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了堡妒?” 一聲冷哼從身側(cè)響起配乱,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎皮迟,沒想到半個月后宪卿,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡万栅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年佑钾,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片烦粒。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡休溶,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出扰她,到底是詐尸還是另有隱情兽掰,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布徒役,位于F島的核電站孽尽,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏忧勿。R本人自食惡果不足惜杉女,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望鸳吸。 院中可真熱鬧熏挎,春花似錦、人聲如沸晌砾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至哼勇,卻和暖如春都伪,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背积担。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工院溺, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人磅轻。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像逐虚,于是被迫代替她去往敵國和親聋溜。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,086評論 2 355

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