0
点赞
收藏
分享

微信扫一扫

一道华为笔试题 ,内存相关

下面一段程序,请说明输出结果:


int _tmain(int argc, _TCHAR* argv[])
{
int *p1,*p2,value;
p1=(int*)0x500;
p2=(int*)0x518;
value=p2-p1;
printf("%d\n", value);
return 0;
}

 结果为6.

(0x518-0x500)/sizeof(int) =6
0x0018/4=6

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

void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str,"helloworld");
printf(str);
}

请问运行Test函数会有什么样的结果?

答:程序崩溃。因为GetMemory并不能传递动态内存,Test函数中的str一直都是NULL。strcpy(str,"helloworld");将使程序崩溃。

char *GetMemory(void)
{
char p[]="helloworld";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}

请问运行Test函数会有什么样的结果?

答:可能是乱码。因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是NULL,但其原先的内容已经被清除,新内容不可知。 

#include   <iostream.h>   

class A
{
unsigned char i;
virtual f() {};
};

class B : public A
{
};

class C : virtual public A
{
};

class D : public B, public C
{
};

void main()
{
cout << "A: " << sizeof(A) << endl;
cout << "B: " << sizeof(B) << endl;
cout << "C: " << sizeof(C) << endl;
cout << "D: " << sizeof(D) << endl;
}
结果为
A: 8
B: 8
C: 12
D: 20

A:1 char+3bit(补位)=4bit+1 ptr=8bit
B:sizeof(B)=0+sizeof(A)=8bit
C:sizeof(A)+1 ptr=12bit
D:sizeof(B)+sizeof(C)=20bit



举报

相关推荐

0 条评论