[英]EXC_BAD_ACCESS error while s[1] = 0; C, Xcode
After I create a string s, I used s[2] = '\0';创建字符串 s 后,我使用了 s[2] = '\0'; to short string s to length of 2. However, it shows me Thread 1: EXC_BAD_ACCESS error.将字符串 s 缩短为 2 的长度。但是,它显示了线程 1:EXC_BAD_ACCESS 错误。 I had changed 2 to other integers but it still gives me the same error.我已将 2 更改为其他整数,但它仍然给我同样的错误。
There may be an issue with your compiler, but the problem as describe works for non-constant strings.您的编译器可能存在问题,但描述的问题适用于非常量字符串。
#include <stdio.h>
int main() {
char s[] = "My String";
s[2] = '\0';
printf("|%s|\n", s);
}
Tested on both clang 13.1.6 and gcc 12:在 clang 13.1.6 和 gcc 12 上测试:
% cc -o EXC EXC.c ; ./EXC
|My|
Clang and gcc both report issues when the declaration is a constant.当声明为常量时,Clang 和 gcc 都会报告问题。 const char s[] = "My String";
EXC.c:6:10: error: cannot assign to variable 's' with const-qualified type 'const char [10]'
s[2] = '\0';
~~~~ ^
EXC.c:4:16: note: variable 's' declared const here
const char s[] = "My String";
~~~~~~~~~~~^~~~~~~~~~~~~~~~~
1 error generated.
EXC.c: In function 'main':
EXC.c:6:10: error: assignment of read-only location 's[2]'
6 | s[2] = '\0';
| ^
Another issue is writing past the end of the string.另一个问题是写到字符串的末尾。 s[10] = '\0';
EXC.c:6:5: warning: array index 10 is past the end of the array (which contains 10 elements) [-Warray-bounds]
s[10] = '\0';
^ ~~
EXC.c:4:5: note: array 's' declared here
char s[] = "My String";
^
1 warning generated.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.