ALEXKK2011

The Technical Side of alexKK2011
  博客园  :: 新随笔  :: 订阅 订阅  :: 管理

pointer & heap & stack

Posted on 2011-02-23 01:02  alexkk2011  阅读(213)  评论(0编辑  收藏  举报
#include <iostream>
#include <string>
 
using namespace std;
 
void main()
{
    //exp.5
    char c[10] = "abc";
    char *charPtr = c; //charPtr & c are in stack
    cout << "char c[10] = \"abc\"\nchar* charPtr=c" << endl;
    cout << "&c is : " << &c << endl;
    cout << "*charPtr is : " << *charPtr << endl;
    cout << "charPtr is : " << charPtr << endl;
    cout << "&charPtr is : " << &charPtr << endl;
    cout << "sizeof(c) is : " << sizeof(c) << endl;
    cout << "sizeof(charPtr) is : " << sizeof(charPtr) << endl;
    cout << "sizeof(*charPtr) is : " << sizeof(*charPtr) << endl << endl; 
 

charPtr = new char[3]; // charPtr in memory: 0x00395ff0 3760112(D)

//charPtr is pointing to the heap

    cout << "charPtr = new char[3]" << endl;
    cout << "*charPtr is : " << *charPtr << endl;
    cout << "charPtr is : " << charPtr << endl;
    cout << "&charPtr is : " << &charPtr << endl;
    cout << "sizeof(charPtr) is : " << sizeof(charPtr) << endl;
    cout << "sizeof(*charPtr) is : " << sizeof(*charPtr) << endl << endl; 
 
    charPtr= (char *)malloc(100) ; // charPtr in memory: 0x003962a8 3760808(D)
    cout << "*charPtr= (char *)malloc(100) " << endl;
    cout << "*charPtr is : " << *charPtr << endl;
    cout << "charPtr is : " << charPtr << endl;
    cout << "&charPtr is : " << &charPtr << endl;
    cout << "sizeof(charPtr) is : " << sizeof(charPtr) << endl;
    cout << "sizeof(*charPtr) is : " << sizeof(*charPtr) << endl << endl; 
 
    free(charPtr);
    cout << "free(charPtr)" << endl;
    //cout << "charPtr is : " << charPtr << endl; //运行时错误:sizeof.exe 中的 0x1026f8e0 (msvcr90d.dll) 处未处理的异常: 0xC0000005: 读取位置 0x00397000 时发生访问冲突
    cout << "*charPtr is : " << *charPtr << endl << endl;
    //charPtr=NULL;
    //cout << "charPtr=NULL" << endl;
    //cout << "*charPtr is : " << *charPtr << endl;
 
    /*
    char c[10] = "abc"
    char* charPtr=c
    &c is : 0012FF54
    *charPtr is : a
    charPtr is : abc
    &charPtr is : 0012FF48
    sizeof(c) is : 10
    sizeof(charPtr) is : 4
    sizeof(*charPtr) is : 1
    charPtr = new char[3]
    *charPtr is :
    charPtr is : 屯妄
    &charPtr is : 0012FF48
    sizeof(charPtr) is : 4
    sizeof(*charPtr) is : 1
    *charPtr= (char *)malloc(100)
    *charPtr is :
    charPtr is : 屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯
    屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯
    &charPtr is : 0012FF48
    sizeof(charPtr) is : 4
    sizeof(*charPtr) is : 1
    free(charPtr)
    *charPtr is :
    请按任意键继续. . .
    */
}