总线错误故障排除 [英] Bus error troubleshooting
问题描述
我试图扭转一个字符串。
I am trying reverse a string.
这是code我尝试:
#include<stdio.h>
#include<string.h>
int main(){
char *c="I am a good boy";
printf("\n The input string is : %s\n",c);
printf("\n The length of the string is : %d\n",strlen(c));
int i,j;
char temp;
int len=strlen(c);
for(i=0,j=len-1;i<=j;i++,j--)
{
temp=c[i];
c[i]=c[j];
c[j]=temp;
//printf("%c\t%c\n",*(c+i),*(c+(len-i-1)));
}
printf("\n reversed string is : %s\n\n",c);
}
在code输出总线错误:10
但是,如果我重写同一code为:
But if I rewrite the same code as:
int main(void)
{
char *str;
str="I am a good boy";
int i,j;
char temp;
int len=strlen(str);
char *ptr=NULL;
ptr=malloc(sizeof(char)*(len));
ptr=strcpy(ptr,str);
for (i=0, j=len-1; i<=j; i++, j--)
{
temp=ptr[i];
ptr[i]=ptr[j];
ptr[j]=temp;
}
printf("The reverse of the string is : %s\n",ptr);
}
这工作完全正常。
It works perfectly fine.
为什么第一个code抛出总线错误或段故障?
Why is the first code throwing bus error or segmentation fault?
推荐答案
因为在许多(如果不是大多数或所有现代)C编译器,字符串在只读存储器分配时发生总线错误。
The bus error occurs because in many (if not most or all modern) C compilers, string literals are allocated in read-only memory.
您正在倒车的地方字符串。在你的第一个code段你试图写入一个字符串。这不是一个好主意。
You are reversing the string in place. In your first code snippet you are trying to write into a string literal. Not a good idea.
在第二种情况下,你malloc分配它把它堆的字符串。现在是安全的,扭转地方的字符串。
In the second case, you malloc'd a string which put it on the heap. It is now safe to reverse that string in place.
附录
要谁问段错误与总线错误的评议,这是一个很大的问题。我已经看到两者。这是在Mac上总线错误:
To the commenter who asked about segfaults versus bus errors, that is a great question. I have seen both. Here is a bus error on a mac:
$ cat bus.c
char* s = "abc"; int main() {s[0]='d'; return 0;}
$ gcc --version bus.c && ./a.out
i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5659)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Bus error
在其他操作系统/编译器,你可能确实得到段错误。
On other operating systems/compilers you may indeed get a segfault.
这篇关于总线错误故障排除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!