- 論壇徽章:
- 17
|
本帖最后由 myworkstation 于 2013-07-03 14:42 編輯
編譯器和語(yǔ)言并沒(méi)有直觀的提供什么功能去實(shí)現(xiàn)這個(gè)處理,可以換個(gè)思路,在C中有四個(gè)存儲(chǔ)類(lèi)型static,automatic,register,dynamic。每種類(lèi)型的存儲(chǔ)的地址都是可識(shí)別的,通過(guò)對(duì)存儲(chǔ)地址的判斷可以識(shí)別實(shí)事的變量或常量變型。
char *a = "hello world";testB (a); 和 testB ("hello world" ); 這兩個(gè)調(diào)用實(shí)際上是一樣的。編譯器在處理的時(shí)候會(huì)把對(duì)hello world的變引指向相同的地方(編譯器基本都這么進(jìn)行優(yōu)化處理,不屬于標(biāo)準(zhǔn)規(guī)定)。根據(jù)上述說(shuō)法那下面的公式成立:編譯器對(duì)常量變量的內(nèi)存處理策略+操作系統(tǒng)的內(nèi)存布局=可明確定位的內(nèi)存識(shí)別。由于操作系統(tǒng)的內(nèi)存布局因系統(tǒng)而定,編譯器的實(shí)現(xiàn)也各有不同,所以就算得出結(jié)論要實(shí)現(xiàn)相關(guān)處理的代碼也是很難進(jìn)行移植的。下面是完成相關(guān)功能的代碼在linux下測(cè)試通過(guò)。- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- int global_dummy = 0;
- static
- void testB (char *src)
- {
- /* 判斷傳入的src 是屬于 @1/2/3/4*/
- int local_dummy = 0;
- if( (unsigned long)src < (unsigned long )&local_dummy ){
- //if( src > testB ){
- if( (unsigned long )src < (unsigned long )&global_dummy ){
- printf("string literal\n\n");
- }
- else if ( (unsigned long ) src > (unsigned long ) &global_dummy){
- printf("malloc string\n\n");
- }
- //}
- }
- else
- {
- printf("array: stack\n\n");
- }
- }
- static
- void testA ()
- {
- char *a = "hello world";
- char b[100] = "hello world";
- char *c = malloc(100);
- strcpy(c,a);
- printf("char *a = \"hello world\";\n");
- testB (a); /* @1 */
- printf("char b[100] = \"hello world\";\n");
- testB (b); /* @2 */
- printf(" (\"hello world\" )\n");
- testB ("hello world" ); /* @3 */
- printf("char *c = malloc(100);\n");
- testB (c ); /* @4 */
- free(c);
- }
- int main(int argc,const char** argv)
- {
- testA();
- return 0;
- }
復(fù)制代碼 程序的運(yùn)行結(jié)果如下:
char *a = "hello world";
string literal
char b[100] = "hello world";
array: stack
("hello world" )
string literal
char *c = malloc(100);
malloc string
下面貼個(gè)linux下程序運(yùn)行的內(nèi)存布局圖,可以加深對(duì)上述代碼的理解
![]() |
|