当前位置:编程学习 > C/C++ >>

学习windows编程(5)修改入口不为mainCRTStartup


上次讲到,如果在VC的console程序中,入口不为mainCRTStartup,会出现什么后果?

我们就先将入口设置为main函数。


1 #include <stdio.h>2 3 int main()4 {5     printf("hello world ");6     return 0;7 }

先通过GUI来设置一下,创建一个win32 console Application。

 image

代码还是差不多,打印字符串

编译链接运行,当然没问题。

修改入口,在”project”->”setting”出现的对话框中,Link选项中,在”Entry-point symbol”中输入main。即定义好入口为main函数。

 image

Rebuild,编译链接,没有问题。

Deleting intermediate files and output files for project Hello - Win32 Debug.
--------------------Configuration: Hello - Win32 Debug--------------------
Compiling...
main.cpp
Linking...

Hello.exe - 0 error(s), 0 warning(s)

运行,出现问题。

 image

来看一下到底是哪里出现了问题。

运行debug版本,切到出错部分。VC界面为:

 image

不知道大家有没有看得清楚,我将call stack单独列在这里,也就是上图中标红线的部分。

NTDLL! 7c9100e8()
_heap_alloc_base(unsigned int 0x00001030) line 161
_heap_alloc_dbg(unsigned int 0x00001000, int 0x00000002, const char * 0x00420c1c `string, int 0x0000003b) line 367 + 9 bytes
_nh_malloc_dbg(unsigned int 0x00001000, int 0x00000000, int 0x00000002, const char * 0x00420c1c `string, int 0x0000003b) line 242 + 21 bytes
_malloc_dbg(unsigned int 0x00001000, int 0x00000002, const char * 0x00420c1c `string, int 0x0000003b) line 163 + 27 bytes
_getbuf(_iobuf * 0x00422a58) line 59 + 19 bytes
_flsbuf(int 0x00000068, _iobuf * 0x00422a58) line 153 + 9 bytes
write_char(int 0x00000068, _iobuf * 0x00422a58, int * 0x0012fd10) line 1083 + 75 bytes
_output(_iobuf * 0x00422a58, const char * 0x0042001d, char * 0x0012ff74) line 393 + 21 bytes
printf(const char * 0x0042001c `string) line 60 + 18 bytes
main() line 5 + 10 bytes
KERNEL32! 7c817077()

可以看到,出错部分是在NTDLL中的某个汇编代码中,但是根源是在printf,printf调用到这部分的时候,结果在_heap_alloc_base的时候出错了,_heap_alloc_base从字面意义上面就可以看出是在堆上分配内存的。

从上面一章,我们又可以得到mainCRTStartup函数在main函数之前调用,其中做了很多初始化工作,其中有一个函数调用叫做_heap_init,是用来创建和初始化CRT堆。而如果直接用main来做入口的话,则没有做这些init工作。

刚刚是通过GUI来创建的,而通过命令行,前面cl编译是一样的,link的时候使用


1 d: est>link /entry:main hello.obj
2 Microsoft (R) Incremental Linker Version 6.00.8168
3 Copyright (C) Microsoft Corp 1992-1998. All rights reserved.同样的效果。

另外,如果不用main,用另外一个函数,比如myentry,会出现什么情况呢?你可以先试试,下一篇来具体说明一下~

 

补充:软件开发 , C语言 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,