作者:
Neisseria (Neisseria)
2016-12-15 16:58:22開發平台(Platform): (Ex: Win10, Linux, ...)
Debian GNU/Linux 和 OS X 10
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
Linux: gcc v4.9.2
OS X: clang-703.0.31
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
無
問題(Question):
我寫了一個本來以為會 segmentation fault 的程式
卻正確地指向特定的資料
餵入的資料(Input):
無
預期的正確結果(Expected Output):
segmentation fault
錯誤結果(Wrong Output):
得到值 16
程式碼(Code):(請善用置底文網頁, 記得排版)
#include <stdio.h>
#include <stdlib.h>
int main() {
const int SIZE = 10;
int* a = (int*) malloc(SIZE * sizeof(int));
int* a1 = a;
for (int i = 0; i < SIZE; i++) {
int j = i + 1;
a[i] = j * j;
}
free(a);
a = NULL;
printf("%d\n", a1[3]);
// segmentation fault if accessing a
// printf("%d\n", a[3]);
return 0;
}
補充說明(Supplement):
感謝 C/C++ 版