[問題] about malloc

看板C_and_CPP (C/C++)作者 (意志決定勝負)時間15年前 (2010/11/08 14:47), 編輯推噓0(0013)
留言13則, 3人參與, 最新討論串1/1
被問到一個問題 char * xxfunction(int size) { char *pt=NULL; if((pt=(char*)malloc(size))==NULL) { printf("error\n"); exit(1); } return pt; } 假如 size傳進來=0 pt仍然可以拿到非NULL的address (malloc(0) 會照常return address) 除了在malloc之前 檢查size是否<0以外 還有其他方法可以避免這個錯誤發生 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 60.251.142.155

11/08 15:00, , 1F
這問題的邏輯很矛盾..為甚麼要傳0? 如果是0 接下來的程
11/08 15:00, 1F

11/08 15:01, , 2F
式應該也不會去用到 像是for(int i = 0 ; i<size ;++i)
11/08 15:01, 2F
用0傳的原因是因為size是外部指定 但是multi access function 的時候有可能拿到錯誤的size值

11/08 15:12, , 3F
看了一下Win的實作 如果malloc傳0 它會配置1的記憶體
11/08 15:12, 3F

11/08 15:12, , 4F
return HeapAlloc(_crtheap, 0, size ? size : 1);
11/08 15:12, 4F

11/08 16:11, , 5F
If the size of the space requested is zero
11/08 16:11, 5F

11/08 16:12, , 6F
, the behavior is implementation defined:
11/08 16:12, 6F

11/08 16:12, , 7F
either a null pointer is returned, or the
11/08 16:12, 7F

11/08 16:13, , 8F
behavior is as if the size were somenonzero
11/08 16:13, 8F

11/08 16:13, , 9F
value, except that the returned pointer shall not
11/08 16:13, 9F

11/08 16:14, , 10F
be used to access an object.
11/08 16:14, 10F

11/08 16:28, , 11F
請參考規格書 7.20.3
11/08 16:28, 11F

11/08 17:15, , 12F
http://codepad.org/uVtb6UCR 簡單寫個這樣的函式就不
11/08 17:15, 12F

11/08 17:15, , 13F
用每次都加 if 去判斷了
11/08 17:15, 13F
※ 編輯: keying 來自: 61.64.138.22 (11/09 14:15)
文章代碼(AID): #1CrvpfPW (C_and_CPP)
文章代碼(AID): #1CrvpfPW (C_and_CPP)