内存四区模型C/C++
1、栈区(stack)—由编译器自动分配释放,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构中的栈。
2、堆区(heap)—一般由程序员分配释放,若程序员不释放,程序结束时可能由OS回收。注意它与数据结构中的堆是两回事,分配方式倒是类似于链表,呵呵。
3、全局区(静态区)(static)—全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域,未初始化的全局变量和未初始化的静态变量在相邻的另一块区域。程序结束后由系统释放。
4、文字常量区—常量字符串就是放在这里的。程序结束后由系统释放。
5、程序代码区
//main.cpp
int a=0; //全局初始化区
char *p1; //全局未初始化区
main()
{
int b;栈
char s[]="abc"; //栈
char *p2; //栈
char *p3="123456"; //123456\0在常量区,p3在栈上。
static int c=0; //全局(静态)初始化区
p1 = (char*)malloc(10);
p2 = (char*)malloc(20); //分配得来得10和20字节的区域就在堆区。
strcpy(p1,"123456"); //123456\0放在常量区,编译器可能会将它与p3所向"123456"优化成一个地方。
}
#include <iostream>
using namespace std;
int main()
{
int *ip = new int;
char s[] = "abcd";
char *p = "abcd";
cout<<ip<<endl; // 地址
cout<<*ip<<endl; // 0
cout<<&ip<<endl; // 一级指针的地址
cout<<endl;
cout<<s<<endl; // abcd
cout<<*s<<endl; // a
cout<<&s<<endl; // 地址
cout<<endl;
cout<<(s+1)<<endl; // bcd
cout<<*(s+1)<<endl; // b
cout<<&s[1]<<endl; // bcd
cout<<endl;
cout<<p<<endl; // abcd
cout<<*p<<endl; // a
cout<<&p<<endl; // 地址
cout<<endl;
cout<<(p+1)<<endl; // bcd
cout<<*(p+1)<<endl; // b
cout<<&p[1]<<endl; // bcd
return 0;
}
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char a[] = "hello";
int b[] = {1,2,3,4,5,6};
char *c = "world";
int * d = new int;
printf("a: %d\n",sizeof(a)/sizeof(char)); // 6
printf("b memory size: %d bytes\n",sizeof(b)); // 24
printf("b elements: %d\n",sizeof(b)/sizeof(int)); // 6
printf("c size: %d\n",sizeof(c)); // 8
printf("c size: %d\n",strlen(c)); // 6
printf("d size: %d\n",sizeof(d)); // 8
cout<<"----------------"<<endl;
int *p = new int;
cout<<*p<<endl; // 0
delete p;
char *p1 = "sdf f";
cout<<p1<<endl; //sdf f
return 0;
}
#include <iostream>
#include <string.h>
int main()
{
char *pp = "abc";
char p[] = "abc";
// std::cout<<strlen(pp)<<std::endl;
// std::cout<<sizeof(p)<<std::endl;
for (int i=0;i<strlen(pp);++i)
{
std::cout<<"() - "<<*(pp+i)<<std::endl;
std::cout<<"[] - "<<pp[i]<<std::endl;
std::cout<<"&[] - "<<&pp[i]<<std::endl;
}
std::cout<<"p--"<<std::endl;
#if 1
for (int i=0;i<sizeof(p);++i)
{
std::cout<<*(p+i)<<std::endl;
std::cout<<p[i]<<std::endl;
std::cout<<&p[i]<<std::endl;
}
#endif
return 0;
}