JasonLi
JasonLi

Reputation: 269

C string manipulating (cutting some special char* tail)

Why here I cannot get "cd fjadf"?
And the program always shows me a Bus error: 10...

I want to use this super_cut_tail() function to cut off ///fjdakf, which is assigned by the user. But why this function cannot achieve that?

char* super_cut_tail(char *char_arg, char *special) {
    char *special_ptr;
    special_ptr = strstr(char_arg, special);
    int len = (int)strlen(char_arg) - (int)strlen(special_ptr);
    char_arg[len] = '\0';
    char_arg = strdup(char_arg);
    return char_arg;
}

int main(int argc, char * argv[])
{
    char *test = "cd fjadf///fjdakf";
    char *outcome;
    outcome = super_cut_tail(test, "///");
    printf("test: %s\n", test);

    return 0;
}

Upvotes: 0

Views: 143

Answers (1)

R Sahu
R Sahu

Reputation: 206737

Your program exhibits undefined behavior since you are modifying the string that was used to initialize test. When you use:

char *test = "cd fjadf///fjdakf";

"cd fjadf///fjdakf" is held in read-only memory of the program. Modifying that string, which you are doing in the line

char_arg[len] = '\0';

is cause for undefined behavior.

Use:

char test[] = "cd fjadf///fjdakf";

The other thing you could do is use:

char const* test = "cd fjadf///fjdakf";

and make a copy of the string first in super_cut_tail before you attempt to modify it.

char* super_cut_tail(char const* char_arg, char *special) {
    char* ret_string = strdup(char_arg);
    char *special_ptr;
    special_ptr = strstr(ret_string, special);
    int len = (int)strlen(ret_string) - (int)strlen(special_ptr);
    ret_string[len] = '\0';
    return ret_string;
}

Upvotes: 2

Related Questions