我正在尝试编写一个就地反向函数,并且几乎完全遵循在线代码,但运行以下程序会引发总线错误。我是否向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;
}
要了解发生了什么,您必须了解 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
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)