[英]Just curiosity, why does this not cause a seg fault?
因此,據我了解,一個C字符串(例如“ 0123456789”)實際上將占用11個字符的數組,主體為10個字符,而終止為null的一個字符。 如果是這樣,那么為什么下面的代碼不會引起某種錯誤?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char ** argv){
char * my_string = "0123456789";
/* my string should occupy 11 bytes */
int my_len = strlen(my_string);
/* however, strlen should only return 10,
because it does not count the null byte */
char * new_string = malloc(my_len);
/* allocate memory 10 bytes wide */
memcpy(new_string, my_string, my_len);
/* copy the first 10 bytes from my_string to new_string
new_string should NOT be null terminated if my understanding
is correct? */
printf("%s\n", new_string);
/* Since new_stirng is NOT null terminated it seems like this should
cause some sort of memory exception.
WHY DOES THIS NOT CAUSE AN ERROR?
*/
return 0;
}
由於new_string
不是以null結尾的,所以我希望printf
永遠讀下去,直到到達其他應用程序的內存,或者在某個位置隨機放置0x00並崩潰或打印出奇怪的東西。 這是怎么回事?
您已經創建了未定義的行為 。 該行為取決於編譯器和平台。 可能會崩潰。 它可以工作。 它可能使您敬酒。 它可能會使您的計算機崩潰,並吸收太陽系。
在您的情況下, new_string[11]
處的內存可能已經為0
,即為'\\0'
或終止空字符。
因為它是未定義的行為。 未定義的行為並不意味着段錯誤,盡管這是一種可能。
在您的情況下,從malloc獲得的特定內存塊之前(程序)從未使用過,並且在分配時可能由OS初始化為零。 因此,第11個字節可能為零,因此沒有錯誤。 在運行時間更長的程序中,malloc可以返回第11個字節不為0的臟內存塊,因此您將在printf語句中遇到問題。 在實踐中,如果分配的區域的末尾沒有null,則將打印垃圾(直到遇到第一個null)。
(正如其他人所說,行為在形式上是不確定的,我只是在解釋您所看到的)。
或在某處隨機放置的0x00 ...打印一些奇怪的東西。
這是通常觀察到的行為。 實際發生的情況是不確定的。
這是未定義的行為。 在某些情況下,它可能導致崩潰,這取決於我想像的內存布局
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.