一、判断变量的存储位置
看一道关于代码的题:
int globalVar = 1;
static int staticGlobalVar = 1;
void Test() {
static int staticVar = 1;
int localVar = 1;
int num1[10] = {1, 2, 3, 4};
char char2[] = "abcd";
char* pChar3 = "abcd";
int* ptr1 = (int*)malloc(sizeof (int)*4);
int* ptr2 = (int*)calloc(4, sizeof(int));
int* ptr3 = (int*)realloc(ptr2,sizeof(int)*4);
free (ptr1);
free (ptr3);
}
//选择题
选项: A.栈 B.堆 C.数据段(全局区、静态区) D.代码段(常量区)
globalVar在哪里?__C__ staticGlobalVar在哪里?_C__
staticVar在哪里?__C_ localVar在哪里?_A__
num1 在哪里?_A__ char2在哪里?__A_
*char2在哪里?_A_ pChar3在哪里?__A_
*pChar3在哪里?_D__ ptr1在哪里?__A_
*ptr1在哪里?__B_
//填空题
sizeof(num1) = _40_;
sizeof(char2) = _5__; strlen(char2) = __4_;
sizeof(pChar3) = _4或8_; strlen(pChar3) = _4_;
sizeof(ptr1) = _4或8_; sizeof(ptr2) = __4或8_;
二、面试题:malloc/calloc/realloc的区别?
这是C语言动态内存管理,在上篇文章已经提过,详情https://blog.csdn.net/a_struggling_monkey/article/details/89500289
三、设计一个类只能在堆上创建对象
分析:1将类的构造函数私有,拷贝构造声明成私有,防止别人调用拷贝在栈上生成对象。
2. 提供一个静态的成员函数,完成堆对象的创建。
class HeapOnly
{
public:
static HeapOnly* GetHeapObj()
{
return new HeapOnly;
}
private:
HeapOnly()
{}
//C++98私有拷贝构造,只声明不实现
HeapOnly(const HeapOnly& hp);
//C++11设置为删除函数
HeapOnly(const HeapOnly& hp)=delete;
};
HeapOnly p3;
int main()
{
HeapOnly *p1 = HeapOnly::GetHeapObj();
//HeapOnly p2 (*p1);//不可以
return 0;
}
四、设计一个类只能在栈上创建对象
方法一:和上面一样,将构造函数私有,然后写一个静态的方法完成栈对象的创建。
class StackOnly
{
public:
static StackOnly GetStackObj()
{
return StackOnly();
}
void Print()
{
cout << "StackOnly::print()" << endl;
}
private:
StackOnly()
{}
};
//StackOnly p3;
int main()
{
StackOnly p1 = StackOnly::GetStackObj();
p1.Print();
StackOnly* p2= new StackOnly;
return 0;
}
方法二:只能在栈上创建对象,即不能在堆上创建,因此只要将new的功能屏蔽掉即可,即屏蔽掉operator new和定
位new表达式,注意:屏蔽了operator new,实际也将定位new屏蔽掉。
class StackOnly
{
public:
StackOnly()
{}
void Print()
{
cout << "StackType::Print()" << endl;
}
private:
void* operator new(size_t n) = delete;
void operator delete(void* p) = delete;
};
StackOnly Obj3;
int main()
{
StackOnly Obj1;
static StackOnly Obj2;
Obj1.Print();
Obj2.Print();
Obj3.Print();
return 0;
}
五、如何一次在堆上申请4G的内存
在一个32位的进程地址空间下,我们最多可以在堆上开辟的空间小于3G,因为有1G是操作系统的。
要想在堆上申请到大于3G的空间可以把运行这个进程的平台换成64位的,在64位的地址空间可以申请到大于3G的堆空间。
// 将程序编译成x64的进程
#include <iostream>
using namespace std;
int main()
{
void* p = new char[0xfffffffful];
cout << "new:" << p << endl;
return 0;
}