要知道发生了什么事,你要明白一个C程序的内存布局。
char *s = "sample"; // Here the "sample" string is placed in
// the read only memory of the Initialized Data segment.
在这里,您不能修改数据。 “s
”是指向char const
(“样本”)的指针,并且您正在尝试修改char const
。这就是为什么你得到bus error
错误。
|Stack frame of main() |
|char *s |
|-------------------------------|
|Stack frame of reverse() |
|char *end |
|char tmp |
| |
|-------------------------------|
| |
| |
| |
| |
| |
|-------------------------------|
| |
| HEAP |
| |
|-------------------------------|
| |
| UNINITIALIZED DATA (BSS) |
| |
|-------------------------------|
| |
| INITIALIZED DATA |
| |
|"sample" | |
| | |
|(Read Only)| (Read/Write) |
|-------------------------------|
| Text or Code Segment |
| |
|-------------------------------|
UPDATE 后下不涉及您的问题。但是如果你知道在C中为所有变量分配的内存在哪里,那么你可以更好地编写代码。 下面的程序可以更好地理解C程序的内存布局。 我没有在图中包含函数的命令行参数,函数参数和返回值。 想要更新这篇文章的人可以将函数的命令行参数,函数参数和返回值添加到图中。
|Stack frame of main() |
|local_To_Main |
| | #include <stdio.h>
|-----------------------------------| #include <stdlib.h>
|Stack frame of function1() | int gVariable1 = 100;
|local_To_Function1 | int gVariable2;
|iptr | char cstring[10] = "Hello";
| \ STACK | char* cptr = "Hello World";
|------\---------------|------------| void function1(void)
| \ \|/ | {
| \ | static int j = 5;
| \ | int local_To_Function1;
| \ ^ | int *iptr;
| \ | | iptr = (int *) malloc(sizeof(int));
|------------\---------------|------| free(iptr);
| HEAP \ --- | }
| \---> |int| |
| --- | int main(void)
|-----------------------------------| {
| | static int i;
| UNINITIALIZED DATA (BSS) | int local_To_Main;
|gVariable2(initialized to 0) |
|i (initialized to 0) |
|-----------------------------------| function1();
| | return 0;
| INITIALIZED DATA | }
| |
|"Hello World" |gVariable1 =100 |
| ^ |cstring="Hello" |
| | |j=5 |
| |---<---<---- cptr |
|(Read Only) | (Read/Write) |
|-----------------------------------|
| Text or Code Segment |
| |
|-----------------------------------|
我相当肯定你的意思'的printf( “%S \ n”,S);'。 – cHao
你应该写'const char * s =“sample”;'。得到它了?你知道为什么字符串常量被称为常量吗?没有?更好地谷歌它。 – 2013-12-26 10:58:50