Chinaunix首页 | 论坛 | 博客
  • 博客访问: 252175
  • 博文数量: 52
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 625
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-03 08:39
文章分类
文章存档

2011年(4)

2010年(5)

2009年(6)

2008年(37)

我的朋友

分类: C/C++

2008-04-12 17:38:57

Getmemory的几个经典的关于内存的笔试题

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

void Test1(void)
{
    char *str = NULL;
    GetMemory1(str);
    strcpy(str, "hello world");
    printf(str);
}
//str一直是空,程序崩溃


char *GetMemory2(void)
{
    char p[] = "hello world";
    return p;
}
void Test2(void)
{
    char *str = NULL;
    str = GetMemory2();
    printf(str);
}
char *GetMemory3(void)
{
     return "hello world";
}
void Test3(void)
{
    char *str = NULL;
    str = GetMemory3();
    printf(str);
}

//Test3 中打印hello world,因为返回常量区,而且并没有被修改过。Test2中不一定能打印出hello world,因为指向的是栈。

void GetMemory4(char **p, int num)
{
    *p = (char *)malloc(num);
}
void Test4(void)
{
    char *str = NULL;
    GetMemory3(&str, 100);
    strcpy(str, "hello");
    printf(str);
}
//内存没释放

void Test5(void)
{
    char *str = (char *) malloc(100);
    strcpy(str, "hello");
    free(str);
    if(str != NULL)
{
   strcpy(str, "world");
   printf(str);
}
}
//str为野指针,打印的结果不得而知

void Test6()
{
    char *str=(char *)malloc(100);
    strcpy(str, "hello");
    str+=6;
    free(str);
    if(str!=NULL)
    {
        strcpy(str, "world");
        printf(str);
    }
}
//VC断言失败,运行错误
 

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