总线错误:10错误
这里是我的代码总线错误:10错误
#import <stdio.h>
#import <string.h>
int main(int argc, const char *argv[])
{
char *str = "First string";
char *str2 = "Second string";
strcpy(str, str2);
return 0;
}
它编译就好了,没有任何警告或错误,但是当我运行的应用程序,我得到这个错误
Bus error: 10
我错过了什么?
其中之一,你不能修改字符串文字。这是未定义的行为。
为了解决这个问题,你可以让str
本地阵列:
char str[] = "First string";
现在,你将有第二个问题,就是str
是不是大到足以容纳str2
。所以你需要增加它的长度。否则,您将超出str
- 这也是未定义的行为。
要解决第二个问题,您需要制作str
至少与str2
一样长。或者动态地分配它:
char *str2 = "Second string";
char *str = malloc(strlen(str2) + 1); // Allocate memory
// Maybe check for NULL.
strcpy(str, str2);
// Always remember to free it.
free(str);
还有其他更优雅的方式来做到这一点涉及沃拉斯(以C99)和堆栈分配,但我不会去到那些为他们的使用是有点怀疑。
由于@SangeethSaravanaraj在评论中指出,每个人都错过了#import
。它应该是#include
:
#include <stdio.h>
#include <string.h>
神秘的,C中支持clang和GCC的'#import',并且是一个Objective-C的扩展。 OP的代码没有问题,因为它只添加了自动包含警卫而没有其他任何内容。 – 2013-01-29 01:33:11
str2
指向一个静态分配的常量字符数组。你不能写信给它。您需要通过*alloc
函数系列动态分配空间。
字符串文字在C中是不可修改的
您的代码尝试覆盖字符串文字。这是未定义的行为。
有几种方法来解决这个问题:
- 使用
malloc()
然后strcpy()
然后free()
; - 将
str
转成数组并使用strcpy()
;使用strdup()
。
没有空间分配给字符串。使用阵列(或)指针与malloc()
和free()
除此之外
#import <stdio.h>
#import <string.h>
应该
#include <stdio.h>
#include <string.h>
注:
- 东西都
malloc()
ED必须free()
“编号 - 您需要分配
n + 1
字节的字符串,它的长度是n
的(最后一个字节是\0
)
请您将以下代码作为参考
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
//char *str1 = "First string";
char *str1 = "First string is a big string";
char *str2 = NULL;
if ((str2 = (char *) malloc(sizeof(char) * strlen(str1) + 1)) == NULL) {
printf("unable to allocate memory \n");
return -1;
}
strcpy(str2, str1);
printf("str1 : %s \n", str1);
printf("str2 : %s \n", str2);
free(str2);
return 0;
}
+1是唯一注意'#import'的人。 – Mysticial 2012-01-03 18:38:44
这是因为str为指向一个字符串字面意味着一个常量字符串......但你试图通过复制来修改它。 注意:如果这是由于内存分配导致的错误,它将在运行时给出分段错误。但是由于字符串修改不断,可能会出现此错误,或者您可以通过以下方式了解更多详细信息abt bus error:
Bus errors are rare nowadays on x86 and occur when your processor cannot even attempt the memory access requested, typically:
- 使用具有不满足 其对准要求的地址的处理器指令。
Segmentation faults occur when accessing memory which does not belong to your process, they are very common and are typically the result of:
- 使用指针的东西,被释放。
- 使用未初始化的伪指针。
- 使用空指针。
- 溢出缓冲区。
更确切地说,这不是操纵指针本身,它会导致问题,它访问它指向的内存(解除引用)。
每当你使用指针变量(星号),如
char *str = "First string";
需要ASIGN内存给它
str = malloc(strlen(*str))
好,'strlen的(STR)
2012-01-03 18:11:26
每个人都缺少'#import'吗?!! – 2012-01-03 18:18:23
@SangeethSaravanaraj是的,我无法相信它自己。大声笑大家都错过了它...... – Mysticial 2012-01-03 18:24:01