开发者社区 问答 正文

为什么这个程序会崩溃

void GetMemory(char *p)
{
    p = (char *)malloc(100);
}
void Test(void) 
{
    char *str = NULL;
    GetMemory(str);   
    strcpy(str, "hello world");
    printf(str);
}

展开
收起
a123456678 2016-06-06 09:57:53 1750 分享 版权
1 条回答
写回答
取消 提交回答
  • #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void GetMemory(char **p)
    {
        *p = (char *)malloc(100);
    }
    
    void Test(void) 
    {
        char *str = NULL;
        GetMemory(&str);   
        strcpy(str, "hello world");
        printf("%s\n", str);
    
        free(str);
        *str = NULL; // 避免误用已悬空的指针
    }
    
    int main(void)
    {
        Test();
        return 0;
    }
    2019-07-17 19:27:43
    赞同 展开评论
问答地址: