作者cord (海派甜心)
看板C_and_CPP
標題[問題] malloc的問題
時間Sat May 17 01:13:22 2014
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
dev-c
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
c語言
問題(Question):
*[36m程式碼(Code):(請善用置底文網頁, 記得排版) *[m
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int main(int argc, char *argv[]) {
int len = 0;
int * pArr = (int*)malloc(sizeof(int)*len);
pArr[0] = 987;
pArr[1] = 100;
pArr[2] = 200;
pArr[3] = 300;
pArr[4] = 400;
printf("%d %d %d %d %d",pArr[0],pArr[1],pArr[2],pArr[3],pArr[4]);
return 0;
}
預期的正確結果(Expected Output):
執行正確 但為什麼len設為零
還是可以印出來 不會出錯
執行結果
987 100 200 300 400
--------------------------------
Process exited with return value 0
Press any key to continue . . .
--
這周是世界好友周,如果你愿意, 請把這條信息發給你所有的好朋友。 也包括我。看有
多少人會回發給你! 世界好友周:務必要看! 出生一張紙,開始一輩子; 畢業一張紙
,奮斗一輩子; 婚姻一張紙,折磨一輩子; 做官一張紙,斗爭一輩子; 金錢一張紙,
辛苦一輩子; 榮譽一張紙,虛名一輩子; 看病一張紙,痛苦一輩子; 悼詞一張紙,了
結一輩子; 淡化這些紙,明白一輩子; 忘了這些紙,快樂一輩子! 當大部分人都在關
注你飛得高不高時, 只有少部分人關心你飛得累不累, 這就是--友情。 再忙,也要照
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.190.224
※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1400260408.A.217.html
※ 編輯: cord (114.43.190.224), 05/17/2014 01:17:17
推 CaptainH:Implementation-defined 05/17 01:34
推 LPH66:沒出事是你運氣好 05/17 01:49
推 firejox:執行正確不代表不會出事.. 05/17 03:17
推 Raymond0710:會發生什麼事你無法確定 05/17 12:59
推 kwpn:我覺得沒出事是運氣不好,等你以後出事,會更難找出問題. 05/17 13:20
謝謝各位大哥大姊的回答
想再請問一下如果拿掉 malloc 前面的強制轉型(int * )
變成這樣寫 int * pArr = malloc(sizeof(int)*len);
為什麼也不會出現錯誤呢 ?
※ 編輯: cord (114.37.158.62), 05/17/2014 14:33:11
→ tomnelson:不強制轉型compile時會有warning吧!? 但你pArr都宣告成 05/17 14:51
→ tomnelson:pointer to int,電腦當然也用pointer to int的結構去操 05/17 14:52
→ tomnelson:作pArr,會出什麼錯誤? 05/17 14:54
→ azureblaze:c void*可以自動轉 c++一定要強制轉 05/17 15:21
推 FreedomMax:c 是不理你 type 的 05/18 13:47