作者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://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1648134616.A.EFF.html
※ 编辑: Kuba4ma (111.251.26.139 台湾), 03/24/2022 23:15:19
1F:推 Schottky: 置底十三诫之第五诫 03/25 00:19
2F:→ breeze08: 第一段是把p内的值回传,然後p这个变数本身的空间(stac 03/25 00:23
3F:→ breeze08: k)被释放,而p回传值所指向的空间(heap)仍然存在 03/25 00:23
4F:→ ctrlbreak: 所以我都建议先学组语XD 03/25 06:39
5F:→ Kuba4ma: 我理解了 谢谢各位大神 03/25 09:04
6F:推 Dracarys: 第一个p指向dynamically allocated的空间,第二段指向s 03/25 09:54
7F:→ Dracarys: tack上的array。你应该是写C吧?那malloc就不用转型。 03/25 09:54
9F:→ Dracarys: Clang会乖乖回传local variable的位址,gcc直接回传0。 03/25 10:04
10F:→ Dracarys: UB的情况code随便compiler生 03/25 10:04
11F:→ yesiah: 先读一下memory layout,弄懂什麽东西在stack什麽在heap 03/25 11:25
12F:推 CoNsTaR: C string literal 其实有和主程式一样的 lifetime 03/29 06:39
13F:→ CoNsTaR: 所以 `p[]` 改 `*p` 或是直接回传 `"hello world"` 就可 03/29 06:39
14F:→ CoNsTaR: 以了 03/29 06:39
15F:嘘 F04E: ..... 03/29 08:57