一道华为笔试题 ,内存相关
2010-03-24 11:24
295 查看
下面一段程序,请说明输出结果:
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
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
相关文章推荐
- [C/C++]一道指针,内存布局的笔试题[摘自CSDN]
- 一道网易笔试题目-几何相关
- C语言测试题目解答:微软一道笔试题,2005年华为招聘
- 一道链表相关的笔试题
- 华为的一道很简单的笔试题,当时答得很烂,现在拿出来重新搞了一下
- 华为的一道笔试题目
- 一道关于内存操作和strcpy的笔试题
- 偶见一道华为笔试题(简单的题更显算法啊--不可忽视的数学)
- 华为一道笔试题:打印2~2000的所有素数,要求尽量快
- 关于华为的一道笔试题(传值和传引用)
- 华为的一道编码笔试题
- 一道关于内存分配的笔试题
- 华为的一道笔试题
- 华为的一道笔试题
- 华为的一道笔试题目:栈的实现
- 一道笔试题(122345求有条件全排列)的两种做法
- C语言编程中分配内存空间的相关函数
- 一道javascript正则笔试题目
- 透过笔试题看C中内存和指针的运用
- 华为2016校园招聘上机笔试题:扑克牌大小 [python]