Chinaunix首页 | 论坛 | 博客
  • 博客访问: 185016
  • 博文数量: 36
  • 博客积分: 230
  • 博客等级: 二等列兵
  • 技术积分: 352
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-22 18:09
文章分类

全部博文(36)

文章存档

2013年(29)

2011年(5)

2010年(2)

我的朋友

分类: C/C++

2013-03-21 10:18:17

void GetMemory(char *p)
{
    p = (char *)malloc(100);
}

void Test(void) 
{
    char *str = NULL;
    GetMemory(str); 
    strcpy(str, "hello world");
    printf(str);
}
请问运行Test函数会有什么样的结果?
答:程序崩溃。
因为GetMemory并不能传递动态内存,
Test函数中的 str一直都是 NULL。
strcpy(str, "hello world");将使程序崩溃。
说的简单一些,就是传入的就是一个空指针,p确实分配空间了,
但是生成的空间首地址没有返回给str

2:
char *GetMemory(void)

    char p[] = "hello world";
    return p;
}
void Test(void)
{
    char *str = NULL;
    str = GetMemory(); 
    printf(str);
}
请问运行Test函数会有什么样的结果?
答:可能是乱码。
因为GetMemory返回的是指向"栈内存"的指针,该指针的地址不是 NULL,但其原现的内容已经被清除,新内容不可知。
说的简单一些,就是函数的局部变量释放了。
3:
void GetMemory2(char **p, int num)
{
    *p = (char *)malloc(num);
}
void Test(void)
{
    char *str = NULL;
    GetMemory(&str, 100);
    strcpy(str, "hello"); 
    printf(str); 
}
请问运行Test函数会有什么样的结果?
答:
(1)能够输出hello
(2)内存泄漏
说的简单一些,就是没有释放malloc的空间

4:
void Test(void)
{
    char *str = (char *) malloc(100);
    strcpy(str, "hello");
    free(str); 
    if(str != NULL)
{
            strcpy(str, "world"); 
            printf(str);
}
}
请问运行Test函数会有什么样的结果?
答:篡改动态内存区的内容,后果难以预料,非常危险。
因为free(str);之后,str成为野指针,
if(str != NULL)语句不起作用。
说的简单一些,就是只收回内存,没有用str=NULL收回指针。

阅读(1039) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~