C/C++ ÄÚ´æ¹ÜÀí Heap vs Stack
תע:
½ñÌìÓÐÍøÓÑÎʵ½Õâ¸öÎÊÌâ,ÓÚÊÇÔÚÍøÉÏËÑË÷ÁËÒ»ÏÂ,תÌùÕâ´Ë.
ÏàËƵÄÌ«¶àÁË,³ö´¦²»Ïê.Ôڴ˸ÐлÔ×÷Õß¾«²Ê½²½â.
Ò»¡¢Ô¤±¸ÖªÊ¶—³ÌÐòµÄÄÚ´æ·ÖÅä
Ò»¸öÓÉ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"ÓÅ»¯³ÉÒ»¸öµØ·½¡£
}
Èý¡¢¶ÑºÍÕ»µÄÀíÂÛ֪ʶ
3.1ÉêÇ뷽ʽ
stack:
ÓÉϵͳ×Ô¶¯·ÖÅä¡£ ÀýÈ磬ÉùÃ÷ÔÚº¯ÊýÖÐÒ»¸ö¾Ö²¿±äÁ¿ int b; ϵͳ×Ô¶¯ÔÚÕ»ÖÐΪb¿ª±Ù¿Õ¼ä
heap:
ÐèÒª³ÌÐòÔ±×Ô¼ºÉêÇ룬²¢Ö¸Ã÷´óС£¬ÔÚcÖÐmallocº¯Êý
Èçp1 = (char *)malloc(10);
ÔÚC++ÖÐÓÃnewÔËËã·û
Èçp2 = (char *)malloc(10);
µ«ÊÇ×¢Òâp1¡¢p2±¾ÉíÊÇÔÚÕ»Öеġ£
3.2 ÉêÇëºóϵͳµÄÏìÓ¦
Õ»£ºÖ»ÒªÕ»µÄÊ£Óà¿Õ¼ä´óÓÚËùÉêÇë¿Õ¼ä£¬ÏµÍ³½«Îª³ÌÐòÌṩÄڴ棬·ñÔò½«±¨Òì³£ÌáʾջÒç³ö¡£
¶Ñ£ºÊ×ÏÈÓ¦¸ÃÖªµÀ²Ù×÷ϵͳÓÐÒ»¸ö¼Ç¼¿ÕÏÐÄÚ´æµØÖ·µÄÁ´±í£¬µ±ÏµÍ³ÊÕµ½³ÌÐòµÄÉêÇëʱ£¬
»á±éÀú¸ÃÁ´±í£¬Ñ°ÕÒµÚÒ»¸ö¿Õ¼ä´óÓÚËùÉêÇë¿Õ¼äµÄ¶Ñ½áµã£¬È»ºó½«¸Ã½áµã´Ó¿ÕÏнáµãÁ´±íÖÐɾ³ý£¬²¢½«¸Ã½áµãµÄ¿Õ¼ä·ÖÅä¸ø³ÌÐò£¬ÁíÍ⣬¶ÔÓÚ´ó¶àÊýϵͳ£¬»áÔÚÕâ¿éÄÚ´æ¿Õ¼äÖеÄÊ×µØÖ·´¦¼Ç¼±¾´Î·ÖÅäµÄ´óС£¬ÕâÑù£¬´úÂëÖеÄdeleteÓï¾ä²ÅÄÜÕýÈ·µÄÊͷű¾ÄÚ´æ¿Õ¼ä¡£ÁíÍ⣬ÓÉ
Ïà¹ØÎĵµ£º
7.2.1 ½éÉÜgetchar()ºÍputchar()
Ç°ÃæµÄ¶àÊý³ÌÐòËùÊäÈëµÄÄÚÈݶ¼ÊÇÊý×Ö¡£ÎªÁËÁ·Ï°Ê¹ÓÃÆäËûµÄÐÎʽ£¬ÈÃÎÒÃÇÀ´¿´Ò»¸öÃæÏò×Ö·ûµÄÀý×Ó¡£
ÏÖÔÚÎÒÃǽ«½Ó´¥×¨ÃÅΪÃæÏò×Ö·ûI/O¶øÉè¼ÆµÄÒ»¶ÔCº¯Êý£ºgetchar()ºÍputchar()¡£
.
getchar()º¯ÊýûÓвÎÊý£¬Ëü·µ»ØÀ´×ÔÊäÈëÉ豸µÄÏÂÒ»¸ö×Ö·û¡£ÀýÈ磬ÏÂÃæµÄÓï¾ä¶ÁÈ¡ÏÂÒ»¸öÊäÈë×Ö·û²¢½«ËüµÄÖµ ......
1. memcpyº¯ÊýµÄʵÏÖ
Ê×ÏȶÔÕâ¸öº¯Êý×öһЩ˵Ã÷¡£
#include <string.h>
void *memcpy(void *to, const void *from, size_t count)
º¯Êýmemcpy()´ÓfromÖ¸ÏòµÄÊý×éÏòtoÖ¸ÏòµÄÊý×鸴ÖÆcount¸ö×Ö·û¡£Èç¹ûÁ½Êý×éÖصþ£¬²»¶¨Ò庯ÊýµÄÐÐΪ¡£
ÔÚC99ÖУ¬toºÍfromÓÉrestrictÐÞÊΡ£
ÏÈÀ´¿´¿´Î¢ÈíµÄʵÏÖ£º
void * __cdecl m ......
ÓÃVIM±àдC/C++³ÌÐò£¨×ªÔØ£©
ÓÃVIM±àдC/C++³ÌÐò
ViÊÇUnixÏÂ×î³£ÓõÄÎı¾±à¼Æ÷¡£VIM£¨Vi IMproved£©ÔòÊÇËüµÄÔöÇ¿°æ¡£ÓÐÈ˳£³£ÄÃVIMºÍemacs±È½Ï£¬VIM¾¡¹Ü²»ÏóemacsÄÇÑùÓÐÄÇô¶àµÄ¹¦ÄÜ£¬µ«ÊDZÈemacs¸ü·½±ã¡¢ºÃÓá£ÓùýemacsµÄÈ˿϶¨»áΪemacsµÄһЩ¿ì½Ý¼ü¸Ðµ½·³ÄÕ£¬ÓÐʱºòÓÃÕæÏ£Íû×Ô¼ºÓаËÖ»ÊÖ¡£VIMµÄѧϰÇúÏßÒ²²»ÏóemacsÄ ......
1.ÒýÑÔ
¡¡¡¡C++ÓïÑԵĴ´½¨³õÖÔÊÇ¡°a better C¡±£¬µ«ÊÇÕâ²¢²»Òâζ×ÅC++ÖÐÀàËÆCÓïÑÔµÄÈ«¾Ö±äÁ¿ºÍº¯ÊýËù²ÉÓõıàÒëºÍÁ¬½Ó·½Ê½ÓëCÓïÑÔÍêÈ«Ïàͬ¡£×÷ΪһÖÖÓûÓëC¼æÈݵÄÓïÑÔ£¬C++±£ÁôÁËÒ»²¿·Ö¹ý³ÌʽÓïÑÔµÄÌص㣨±»ÊÀÈ˳ÆΪ¡°²»³¹µ×µØÃæÏò¶ÔÏó¡±£©£¬Òò¶øËü¿ÉÒÔ¶¨Òå²»ÊôÓÚÈκÎÀàµÄÈ«¾Ö±äÁ¿ºÍº¯Êý¡£µ«ÊÇ£¬C++±Ï¾¹ÊÇÒ»ÖÖÃæÏò¶ ......