Chinaunix首页 | 论坛 | 博客
  • 博客访问: 496873
  • 博文数量: 111
  • 博客积分: 3160
  • 博客等级: 中校
  • 技术积分: 1982
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-24 11:49
个人简介

低调、勤奋。

文章分类

全部博文(111)

文章存档

2014年(2)

2013年(26)

2012年(38)

2011年(18)

2010年(27)

分类: C/C++

2010-04-30 16:00:13

常见的内存测试题:

试题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 字节
}

试题7
#include
#include

int main()
{
        int arr[] = {6,7,8,9,10};
        int *ptr = arr;
        printf("%d \n",*(ptr++) += 123);   
        printf("%d -- %d \n", *ptr, *(++ptr));
        printf("%d -- %d \n", *ptr, *(ptr));
}

结果 
129
8 8
8 8


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

chinaunix网友2010-05-05 13:09:06

测试题4:实践中好像不大建议置空一个 被释放的指针。你释放的时候知道你不想用了,之后用它做什么在语意上都是不合适的。阅读代码的时候很让人迷惑。如果我找问题,我先说那个if很有问题。 测试题6:sizeof的实现可能是和编译器有关的。没看过最新的C标准。