0

以下のプログラムでは、

#include<stdio.h>
#include<stdlib.h>
int main(){
  const char *str1 = "abc";
  char *str2 = (char *)malloc(sizeof(char)*4);
  str2= "def";
  str2[1]='s';
  printf("str2 is %s", str2);

}

デバッガ:

(gdb) ptype str1                                                                                                                         
type = const char *                                                                                                                      
(gdb) ptype str2                                                                                                                         
type = char *                                                                                                                            
(gdb) n                                                                                                                                  
7         str2[1]='s';                                                                                                                   
(gdb) n               

Program received signal SIGSEGV, Segmentation fault.                                                                                     
0x00000000004005ab in main () at main.c:7                                                                                                
7         str2[1]='s';                                                                                                                   
(gdb)

SIGSEGV オンstr2[1] = 's';

私の理解によると、文字列リテラルが定数である宣言のために、によってabc指されたを変更することはできません。st1const char *st1 = "abc"

char *typestr2が要素の変更を許可しないのはなぜですか? stringliteraldefも定数文字列リテラルです。

4

5 に答える 5

0

このstr2 = "def";ステートメントは の値を変更しますstr2str2次のクラッシュにつながる割り当ての後の文字列リテラル「def」を指します。少なくとも、私の RHEL 7.1 と gcc 4.8.3 ではそうです。

于 2016-10-20T05:28:01.663 に答える