Why does this small C program crash?

后端 未结 4 430
有刺的猬
有刺的猬 2021-01-28 12:33

The program is:

#include 
#include 
int main(void) {
    char *a=\"abc\",*ptr;
    ptr=a;
    ptr++;
    *ptr=\'k\';
    printf(\"         


        
4条回答
  •  伪装坚强ぢ
    2021-01-28 12:56

    The problem is because you are trying to change the string literal "abc" with:

    char *a="abc",*ptr;
    ptr=a;                  // ptr points to the 'a'.
    ptr++;                  // now it points to the 'b'.
    *ptr='k';               // now you try to change the 'b' to a 'k'.
    

    That's undefined behaviour. The standard explicitly states that you are not permitted to change string literals as per section 6.4.5 String literals of C99:

    It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

    It will work if you replace:

    char *a="abc",*ptr;
    

    with:

    char a[]="abc",*ptr;
    

    since that copies the string literal to a place that's safe to modify.

提交回复
热议问题