Chinaunix首页 | 论坛 | 博客
  • 博客访问: 250015
  • 博文数量: 78
  • 博客积分: 1465
  • 博客等级: 上尉
  • 技术积分: 972
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-28 13:46
文章分类

全部博文(78)

文章存档

2012年(1)

2011年(9)

2010年(68)

我的朋友

分类: C/C++

2010-05-13 23:43:33

常见的内存测试题:

试题1:
void GetMemory( char *p )
{

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


典型的值传递,而非地址传递,只能改变形参值,不能改变其实参值。

如果要解决该问题,怎么做,下面的实例:


void GetMemory( char **p )
{

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


解决方法采用:指向指针的指针变量,传进去的str的地址,这样就可以了。


试题2:
char *GetMemory( void )
{
    char p[] = "hello world";
    return p;   
 }
void Test( void )
{
    char *str = NULL;
    str = GetMemory();
    printf( str );

典型的例子,数组作为地址返回时,是指向“栈内存”的指针,内容已经被清除掉,是个野指针。

试题3:

void GetMemory( char **p, int num)
{

   *p = (char *)malloc(num);   
 
}

void Test( void )
{
    char *str = NULL;
    GetMemory(&str, 100);
    strcpy(str, "hello");
    printf(str);

错误:
1、未对申请到的内存进行判断,有可能申请未成功。
2、未释放内存

试题4:

 void Test(void)
{
    char *str = (char *) malloc(100);
    strcpy(str, “hello”);
    free(str);

 if(str != NULL)
 {
    strcpy(str, “world”);
    printf(str);
 }
}
错误:
1、free str 后,str成为野指针,需要置空。
str = NULL;

试题5.判断是否为空的问题
   BOOL型变量:if(!var)
   int型变量: if(var==0)
   float型变量:
   const float EPSINON = 0.00001;
   if ((x >= - EPSINON) && (x <= EPSINON)
   指针变量:  if(var==NULL)

试题6.
计算内存容量

char a[] = "hello world";
char *p = a;
cout<< sizeof(a) << endl; // 12 字节
cout<< sizeof(p) << endl; // 4 字节
注意:数组作为函数的参数
void Func(char a[100])
{
cout<< sizeof(a) << endl; // 4 字节而不是100 字节
}

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