在小型c程序中获得分段错误
我写了一个小编:
1 #include 2 main(){ 3 char* str = "string"; 4 *str = 'k'; 5 printf("string is = %s\n",str); 6 }
编译该程序时没有任何错误或警告,但是当我运行它时,它会给出分段错误。 如果我将第3行重写为:char str [] =“string”; 这个程序非常好。 任何人都可以让我知道这里有什么问题??? 编写第3行的这两种不同方式之间有什么区别。 任何帮助将不胜感激。 谢谢。
char * str = "string";
声明一个指针,指向存储字符串"string"
的内存区域; 在这个内存区域写入是未定义的行为,它通常会导致崩溃。
相反,你应该使用:
char str[]="string";
它声明了一个函数本地的字符串,它被初始化为值"string"
。 由于您用于此字符串的内存对于您的过程是本地的,因此您可以根据需要对其进行更改。
char* str = "string";
这将字符串放在只读内存中。 当您尝试使用下一行修改它时,它是未定义的行为(通常是令人不快的行为)。 尝试类似的东西
char str[] = "string";
代替。
I also executed the given code.. 1 #include 2 main(){ 3 char* str = "string"; 4 *str = 'k'; 5 printf("string is = %s\n",str); 6 } But there is no such error. Following output is shown.... String is=Ktring A segmentation fault, bus error, or access violation is generally an attempt to access memory that the CPU cannot physically address. So in my opinion it's completely depends on execution. thanks...