且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关于malloc内存申请的深入研究

更新时间:2022-10-03 13:57:40

在内存申请和使用上总是会出现一些莫名其妙的问题,今天刚好又碰到了,这里总结一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//1.编译可以通过,但是执行不过。卡死在注释那一句
void test()
{
    char * str = (char *)malloc(100);
    strcpy(str,"hello");
    free(str);
    if(str != NULL)
    {
        strcpy(str,"world");
        printf("%s\n",str);//因为str已经free,所以对str的访问出现问题,卡死在这一步
    }
}
//---------------------------------------
//2.双指针是OK的
void getMemory(char **p,int num)
{
    *p = (char *)malloc(num);
}
 
void test()
{
    char *str = NULL;
    getMemory(&str,100);
    strcpy(str,"hello");
    printf("%s\n",str);
}
 
//-----------------------------------------
//3.编译通过,执行通过,返回垃圾文字。
char * getmemory()
{
    char p[] = "hello world";
    return p;
}
 
void test()
{
    char *str = NULL;
    str = getmemory();
    printf("%s\n", str);//因为getmemory()中返回的是局部变量的地址,
    //所以在getmemory()执行完毕后,该变量自动释放。所以访问失败。输出一些垃圾文字。
}
//-----------------------------------------
//4.编译通过,执行失败。
void getmemory(char *p)
{
    p = (char *)malloc(100);//内存空间申请后,指向这一空间的指针被释放
}
 
void test()
{
    char *str = NULL;
    getmemory(str);
    strcpy(str, "hello world");//str没有空间来容纳后面的字符串
    printf("%s\n", str);
}



本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1852158