最近寫程序遇到一個比較離奇 的程序
簡單如下:
char *p="abc";
*(p+1)='B';
puts(p);
*(p+1)='B';
puts(p);
居然不對,沒有正確的運行結果,後來在網絡上查到了,原來是C語言中內存單元分區問題。
/*下面內容來自網絡*/
一個由C/C++編譯的程序佔用的內存分爲以下幾個部分
1、棧區(stack)— 由編譯器自動分配釋放 ,存放函數的參數值,局部變量的值等。其
操作方式類似於數據結構中的棧。
2、堆區(heap) — 一般由程序員分配釋放, 若程序員不釋放,程序結束時可能由OS回收 。注意它與數據結構中的堆是兩回事,分配方式倒是類似於鏈表。
3、全局區(靜態區)(static)—,全局變量和靜態變量的存儲是放在一塊的,初始化的全局變量和靜態變量在一塊區域,未初始化的全局變量和未初始化的靜態變量在相鄰的另一塊區域。程序結束後由系統釋放。
4、文字常量區 — 常量字符串就是放在這裏的。程序結束後由系統釋放 。
5、程序代碼區—存放函數體的二進制代碼。
1、棧區(stack)— 由編譯器自動分配釋放 ,存放函數的參數值,局部變量的值等。其
操作方式類似於數據結構中的棧。
2、堆區(heap) — 一般由程序員分配釋放, 若程序員不釋放,程序結束時可能由OS回收 。注意它與數據結構中的堆是兩回事,分配方式倒是類似於鏈表。
3、全局區(靜態區)(static)—,全局變量和靜態變量的存儲是放在一塊的,初始化的全局變量和靜態變量在一塊區域,未初始化的全局變量和未初始化的靜態變量在相鄰的另一塊區域。程序結束後由系統釋放。
4、文字常量區 — 常量字符串就是放在這裏的。程序結束後由系統釋放 。
5、程序代碼區—存放函數體的二進制代碼。
=========================
另:
相關解釋:
相關解釋:
C99標準 第130頁
32 EXAMPLE 8 The declaration
char s[] = "abc", t[3] = "abc";
defines "plain" char array objects s and t whose elements are initialized with character string
literals.
This declaration is identical to
char s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable.
On the other hand, the declaration
char *p = "abc";
defines p with type "pointer to char" and initializes it to point to an object with type
"array of char" with length 4 whose elements are initialized with a character string literal.
If an attempt is made to use p to modify the contents of the array, the behavior is undefined.
32 EXAMPLE 8 The declaration
char s[] = "abc", t[3] = "abc";
defines "plain" char array objects s and t whose elements are initialized with character string
literals.
This declaration is identical to
char s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable.
On the other hand, the declaration
char *p = "abc";
defines p with type "pointer to char" and initializes it to point to an object with type
"array of char" with length 4 whose elements are initialized with a character string literal.
If an attempt is made to use p to modify the contents of the array, the behavior is undefined.
所以在char* p = "abc"; 中
C語言標準並沒有規定是否可以通過p修改"abc",
如果用p修改"abc",那麼行爲是未定義的
在某些編譯器下會正確
在某些編譯器下會錯誤
如果用p修改"abc",那麼行爲是未定義的
在某些編譯器下會正確
在某些編譯器下會錯誤