作者Kuba4ma ()
看板C_and_CPP
標題[問題] 記憶體位址回傳問題
時間Thu Mar 24 23:10:14 2022
1.
char* GetMemory() {
char* p = (char *)malloc(100);
return p;
}
void test() {
char *str = NULL;
str = GetMemory();
strcpy(str, "hello world");
printf("%s\n", str);
}
int main(){
test();
}
2.
char* GetMemory() {
char p[] = "hello world";
return p;
}
void test() {
char *str = NULL;
str = GetMemory();
printf(str);
}
int main(){
test();
}
第一段的code會印出"hello world" 但是第二段不會
我的問題是
第二段code的GetMemory內做陣列宣告 不也是會配置記憶體給 p 嗎?
那麼做的事情和第一段code的GetMemory一樣
為什麼不會印出"hello world"
如果第二段code的p會因為function結束而不見的話
為什麼第一段code的p不會消失
謝謝大家
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.251.26.139 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1648134616.A.EFF.html
※ 編輯: Kuba4ma (111.251.26.139 臺灣), 03/24/2022 23:15:19
推 Schottky: 置底十三誡之第五誡 03/25 00:19
→ breeze08: 第一段是把p內的值回傳,然後p這個變數本身的空間(stac 03/25 00:23
→ breeze08: k)被釋放,而p回傳值所指向的空間(heap)仍然存在 03/25 00:23
→ ctrlbreak: 所以我都建議先學組語XD 03/25 06:39
→ Kuba4ma: 我理解了 謝謝各位大神 03/25 09:04
推 Dracarys: 第一個p指向dynamically allocated的空間,第二段指向s 03/25 09:54
→ Dracarys: tack上的array。你應該是寫C吧?那malloc就不用轉型。 03/25 09:54
→ Dracarys: Clang會乖乖回傳local variable的位址,gcc直接回傳0。 03/25 10:04
→ Dracarys: UB的情況code隨便compiler生 03/25 10:04
→ yesiah: 先讀一下memory layout,弄懂什麼東西在stack什麼在heap 03/25 11:25
推 CoNsTaR: C string literal 其實有和主程式一樣的 lifetime 03/29 06:39
→ CoNsTaR: 所以 `p[]` 改 `*p` 或是直接回傳 `"hello world"` 就可 03/29 06:39
→ CoNsTaR: 以了 03/29 06:39
噓 F04E: ..... 03/29 08:57