C 中 printf 的不逻辑总线错误
当我编译并运行代码时,在打印“开始”后立即出现总线错误。 发生的情况如下:
bash-3.2$ ./remDup
开始
总线错误
#include <stdio.h>
#include <string.h>
void removeDups(char* str)
{
int len = strlen(str);
int i = 0;
for (i = 0; i < len; i++) {
char a = str[i];
int k = i + 1;
int c = 0;
int j = 0;
for (j = k; j < len; j++) {
if (a != str[j]) {
str[k] = str[j];
k++;
} else c++;
}
len -= c;
}
str[len] = '\0';
}
int main(int argc, const char* argv[] )
{
char *str1 = "apple";
printf("%s -> ", str1);
removeDups(str1);
printf("%s\n ", str1);
return 1;
}
When I compile and run my code, I get a bus error right after it prints "starting."
Here is what happens:
bash-3.2$ ./remDup
starting
Bus error
#include <stdio.h>
#include <string.h>
void removeDups(char* str)
{
int len = strlen(str);
int i = 0;
for (i = 0; i < len; i++) {
char a = str[i];
int k = i + 1;
int c = 0;
int j = 0;
for (j = k; j < len; j++) {
if (a != str[j]) {
str[k] = str[j];
k++;
} else c++;
}
len -= c;
}
str[len] = '\0';
}
int main(int argc, const char* argv[] )
{
char *str1 = "apple";
printf("%s -> ", str1);
removeDups(str1);
printf("%s\n ", str1);
return 1;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您将字符串定义为:
您不允许修改内容 - 标准非常清楚这是未定义的行为(a)。使用:
相反,它会给你一个可修改的副本。它在功能上等同于:
(a) C99
6.4.5“字符串文字”
,段落6
指出:If you define a string as:
you are not permitted to modify the contents - the standard is quite clear that this is undefined behaviour (a). Use:
instead and it will give you a modifiable copy. It's functionally equivalent to:
(a) C99
6.4.5 "String literals"
, paragraph6
states:您正在修改通常驻留在只读内存中的字符串文字。该标准还规定尝试修改文字是未定义的行为。
当您使用指向字符串文字的指针时,您应该将它们声明为 const、const char * str="text"; 或数组
char str[] = "text";< /code>
更改为例如:
在这种情况下,编译器将在堆栈上创建一个数组,并将只读字符串文字复制到其中。
You're modifying string literals which often reside in read-only memory. The standard also states that attempting to modify literals is undefined behavior.
When you're using pointers to string literals, you should either declare them as const,
const char * str="text";
or as arrayschar str[] = "text";
Change to e.g:
In this case the compiler will create an array on stack, and copy the read-only string literal into it.