use*_*163 1 c memory reverse pointers
我正在尝试编写就地反向函数并且几乎完全遵循在线代码,但运行以下程序会引发总线错误.我是否将错误的参数传递给reverse()?
void reverse(char *str) {
char * end = str;
char tmp;
if (str) {
while (*end) {
++end;
}
--end;
while (str < end) {
tmp = *str;
*str++ = *end;
*end-- = tmp;
}
}
}
int main() {
char *s = "sample";
reverse(s);
printf("%s\n");
return 1;
}
Run Code Online (Sandbox Code Playgroud)
小智 16
要知道发生了什么,您必须了解C程序的内存布局.
char *s = "sample"; // Here the "sample" string is placed in
// the read only memory of the Initialized Data segment.
Run Code Online (Sandbox Code Playgroud)
在这里,您无法修改数据." 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 |
| |
|-------------------------------|
Run Code Online (Sandbox Code Playgroud)
更新 以下帖子与您的问题无关.但是如果你知道在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 |
| |
|-----------------------------------|
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1592 次 |
| 最近记录: |