问题描述
下面是我的code
#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;
}
它编译没有任何警告或错误就好了,但是当我运行应用程序我得到这个错误
It compiles just fine without any warning or errors, but when I run the app I get that error
Bus error: 10
我错过了什么?
推荐答案
首先,你不能修改字符串常量。这是未定义的行为。
For one, you can't modify string literals. It's undefined behavior.
要解决这个问题,你可以让 STR
本地数组:
To fix that you can make str
a local array:
char str[] = "First string";
现在,你将有第二个问题,就是 STR
不是大到足以容纳 STR2
。所以,你需要增加它的长度。否则,你会溢出 STR
- 这也是不确定的行为
Now, you will have a second problem, is that str
isn't large enough to hold str2
. So you will need to increase the length of it. Otherwise, you will overrun str
- which is also undefined behavior.
要解决这个第二个问题,您可能需要做出 STR
至少只要 STR2
。或动态分配的:
To get around this second problem, you either need to make str
at least as long as str2
. Or allocate it dynamically:
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)和堆栈分配,但我不会去那些为它们的使用是有点怀疑的。
There are other more elegant ways to do this involving VLAs (in C99) and stack allocation, but I won't go into those as their use is somewhat questionable.
由于@SangeethSaravanaraj在评论中指出的那样,每个人都错过了#进口
。它应该是的#include
:
As @SangeethSaravanaraj pointed out in the comments, everyone missed the #import
. It should be #include
:
#include <stdio.h>
#include <string.h>
这篇关于总线错误:错误10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!