专注于C,C++,VC,PYTHON等技术
There should be one-- and preferably only one --obvious way to do it.
2008年4月18日
printf都做了什么??
最近在看以前的一些代码,发现程序中有一些函数返回指针,而且所返回的指针是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)
|
编辑
收藏
仅列出标题
导航
C++博客
首页
新随笔
联系
聚合
管理
<
2008年11月
>
日
一
二
三
四
五
六
26
27
28
29
30
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
1
2
3
4
5
6
统计
随笔 - 1
文章 - 1
评论 - 5
引用 - 0
常用链接
我的随笔
我的评论
我参与的随笔
留言簿
给我留言
查看公开留言
查看私人留言
随笔档案
2008年4月 (1)
文章档案
2008年4月 (1)
搜索
最新评论
1. re: printf都做了什么??[未登录]
评论内容较长,点击标题查看
--lynn
2. re: printf都做了什么??
评论内容较长,点击标题查看
--starofrainnight
3. re: printf都做了什么??
评论内容较长,点击标题查看
--啸天猪
4. re: printf都做了什么??
评论内容较长,点击标题查看
--lonkil
5. re: printf都做了什么??[未登录]
昏。在栈上的数据嘛,肯定没有问题了。
--steven