Bdcom笔试题

C中内存分配的问题:

1.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
 
void GetMemory(char **p)
{
    *p=(char *)malloc(100);
}
 
void Test()
{
    char **str;
    GetMemory(str);
 
    strcpy(*str, "hello world");
    printf("str is%s", *str);
}
 
int main()
{
    Test();
 
    system("PAUSE");
    return 0;
}

结果:运行时错误

GetMemory并没有正确分配内存,str开始为NULL,传入参数后p为NULL,对它解引用*p当然会出错

正确的改法:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
 
void GetMemory(char **p)
{
    assert(p!=NULL);
    *p=(char *)malloc(100);
}
 
void Test()
{
    char *str=NULL;
    GetMemory(&str);
 
    strcpy(str, "hello world");
    printf(str);
}
 
int main()
{
    Test();
 
    system("PAUSE");
    return 0;
}

------------------------------------------------------------------------------------------------------------------------------------------------

2.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
 
char *GetMemory()
{
    return "hello world";
}
 
void Test()
{
    char *str=NULL;
    str=GetMemory();
    printf(str);
}
 
int main()
{
    Test();
 
    system("PAUSE");
    return 0;
}

打印:hello world

GetMemory返回的指针指向只读区,但是Test函数中并没有进行写操作,所以打印正确

-----------------------------------------------------------------------------------------------------------------------------------------------

3.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
 
struct para
{
    char str[11];
    char len;
};
 
void GetMemory(char p[11], char *len)
{
    *len=strlen("hello world");
    strcpy(p, "hello world");
}
 
void Test()
{
    struct para a;
    int i;
    GetMemory(a.str, &a.len);
    printf("%d", a.len);
    for(i=0; i<a.len;++i)
    {
        printf("%c", a.str[i]);
    }
}
 
int main()
{
    Test();
 
    system("PAUSE");
    return 0;
}

 

-----------------------------------------------------------------------------------------------------------------------------------------------

4.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
 
void Test()
{
    char *str=(char *)malloc(100);
    strcpy(str, "hello");
    str+=6;
    free(str);
    if(str!=NULL)
    {
        strcpy(str, "world");
        printf(str);
    }
}
 
int main()
{
    Test();
 
    system("PAUSE");
    return 0;
}

GCC打印:world

VC:assertion failed, 运行时错误

str已经后移了6位,再free。不明白这样做是什么意思,应该是不允许的吧!!!(VC的确断言失败,运行错误,gcc却没用)

但是str一定不为NULL,其指向的内存应该不确定才对。但是很遗憾,编译和运行在这里均没用报错



倒数第2题:
设计一个计算器,已知输入都存入了char buff[]中

最后一题:
背包问题,递归和非递归算法
posted @ 2007-12-06 18:46  中土  阅读(626)  评论(0编辑  收藏  举报
©2005-2008 Suprasoft Inc., All right reserved.