Try   HackMD
tags: blog, programming-note

字串(字元陣列 char str[])與字元指標(char* str)的關係

#include <stdio.h>

int main(){
    char* str = NULL;
    gets(str);
    printf("%s\n", str);
    return 0;
}

這樣的程式碼在編譯時是沒有問題的,

但在執行的時候,輸入完字串就會出現以下錯誤並結束程式:

Segment fault (core dumped)

為什麼呢?不是說在 C 裡面,字串是字元陣列,且陣列名稱代表指向陣列的指標嗎?

其實仔細想想,char* 是個指向字元的指標,char* str = "hello, world" 之所以可行,是因為它指向的是 hello, world 這個 literal 的關係。

這篇文章裡面提到,

char str[] = "hello, world"

char* str = "hello, world"

所代表的意義是不一樣的,前者是個陣列,後者則如前述所說,是個指向 literal 的指標。

因此,前述程式碼應改成:

#include <stdio.h>

int main(){
    char str[MAX_SIZE];
    gets(str);
    printf("%s\n", str);
    return 0;
}

並注意輸入的字串長度不能超過 MAX_SIZE

其實超過了也還是可以繼續執行,但在程式結束時會有以下錯誤情況:

*** stack smashing detected ***
Aborted (core dumped)

根據這篇文章

An input of string greater than size 10 causes corruption of gcc inbuilt protection canary variable followed by SIGABRT to terminate the program.You can disable this protection of gcc using option 即:stack smashing 是 GCC 的一种检测 “缓存溢出” 的保护机制.当分配的内存不够时,会继续执行;但是在程序结束返回时才出现错误提示

其原因為拜訪陣列時超過了陣列的合法長度,但程式會幫你延長,在結束執行時才告訴你錯誤。


如果你喜歡這篇文章,請按照程度替我按 1~5 個讚!
歡迎加入讚賞公民的行列!不需要花費任何金錢,只要你辦個帳號就可以按讚了!