Illogical bus error from printf in C
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;
开发者_如何学Go 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;
}
If you define a string as:
char *str1 = "apple";
you are not permitted to modify the contents - the standard is quite clear that this is undefined behaviour (a). Use:
char str1[] = "apple";
instead and it will give you a modifiable copy. It's functionally equivalent to:
char str1[6]; strcpy (str1, "apple");
(a) C99 6.4.5 "String literals"
, paragraph 6
states:
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
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 arrays char str[] = "text";
Change to e.g:
char str1[] = "apple";
In this case the compiler will create an array on stack, and copy the read-only string literal into it.
精彩评论