2008年4月18日

最近在看以前的一些代码,发现程序中有一些函数返回指针,而且所返回的指针是stack指针,觉得很是奇怪,stack指针都是系统自己维护,出了作用域以后自动释放的,难道函数所返回的stack指针还能继续使用?以前的代码就是那样,而且运行也一直很正常,这是什么原因?觉得很是怪异。
为测试stack指针是否由系统管理,从函数中返回后是否继续可用,写了一些代码:
// TestPointer.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include 
<windows.h>
#include 
<stdlib.h>

typedef 
struct Person
{
    
int iAge;
    
int iWeight;
}
Person;

//Printf都做了什么?
//感觉调用printf时系统对stack进行了清理
char * GetString(void);
Person 
* GetPerson();

int main(int argc, char* argv[])
{
    printf(
"Hello World!\n");

    
char * pStr = GetString();

    
//感觉调用printf时系统对stack进行了清理
    printf("%s", pStr); //将这一句去掉后运行试试?

    Person 
* m_pPersion = GetPerson();
    
    printf(
"doooooo\n"); //将这一句去掉运行试试?
    printf("Age = %d, Weight = %d\n", m_pPersion->iAge, m_pPersion->iWeight);

    
return 0;
}


char * GetString(void)
{
    
//简单的可以理解为: 
    
//heap:是由malloc之类函数分配的空间所在地。地址是由低向高增长的。 
    
//stack:是自动分配变量,以及函数调用的时候所使用的一些空间。地址是由高向低减少的。
    
//栈(stack)内存的情况
    char szMessage[100];
    strcpy(szMessage, 
"this is just a test!\n");
    printf(
"%s", szMessage);
    
return szMessage;

    
//堆(heap)内存的情况
    /*char * pRet = (char *)malloc( 100 * sizeof(char));
    strcpy(pRet, "This is just a test!\n");
    return pRet;
*/
    
}


Person 
* GetPerson()
{
    
//stack
    Person m_Person;
    m_Person.iAge 
= 24;
    m_Person.iWeight 
= 55;

    
return &m_Person;

    
//更换成heap形式的又是怎样?
}


上述程序运行环境为:WindowsXP sp2 
+ Visual C++ Enterprise Edition 6.0 + Vs6Sp6
源代码
posted @ 2008-04-18 20:32 犹志 阅读(1132) | 评论 (5)编辑 收藏
仅列出标题  

导航

<2008年11月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

统计

常用链接

留言簿

随笔档案

文章档案

搜索

最新评论