可能重複:
Invalid read/write sometimes creates segmentation fault and sometimes does not爲什麼運行這不會產生分段錯誤?
我有以下代碼:
#include <stdlib.h>
#include <stdio.h>
int main() {
int *ptr = NULL;
ptr = malloc(sizeof(char));
if (ptr) {
*ptr = 10;
printf("sizeof(int): %zu\nsizeof(char): %zu\n", sizeof(int), sizeof(char));
printf("deref of ptr: %d\n", *ptr);
free(ptr);
return EXIT_SUCCESS;
}
else
return EXIT_FAILURE;
}
當我編譯並運行它,我得到以下輸出:
$ gcc test.c
$ ./a.out
sizeof(int): 4
sizeof(char): 1
deref of ptr: 10
值sizeof(char)
小於sizeof(int)
。我的malloc
呼叫只留出足夠的空間用於char
。但是,我的程序能夠在不崩潰的情況下爲ptr
分配一個整數值。爲什麼這個工作?
你可能想看看這個問題及其答案的指導:http://stackoverflow.com/questions/8641478/invalid-read -write-sometimes-creating-segmentation-fault-and-sometimes-does-not – 2012-01-01 21:58:16
C不一定會遵守變量'boundries',所以你可能會覆蓋內存中的一些隨機3字節, 。 – 2012-01-01 22:01:29
'sizeof(char)'總是1(6.5.3.4,§3)。 – 2012-01-01 22:04:41