Kyle Uithoven Kyle Uithoven - 2 months ago 8
C Question

Replace a character in a char[] from a function

How would I get my replace_char function to work properly?

The way that I am trying it in the function below returns segmentation faults using gcc in Ubuntu.

I have tried other ways, but each time I try to change the value, I get a fault.

int main (void)
{
char* string = "Hello World!";

printf ("%s\n", string);
replace_char(string, 10, 'a');
printf ("%s\n", string);
}

void replace_char(char str[], int n, char c)
{
str[n] = c;
}

Answer

Edit

To get the 'suggestion' of editing string in place, you can edit the pointer inplace:

void replace_char(char*& str, int n, char c)
{
  str = strdup(str);
  str[n] = c;
}

int main()
{
    char* string = "Hello World!";
    string = replace_char(string, 10, 'a');

    // ...
    free(string);
}

Note you now have to remember to call free on the string after calling this. I suggest, instead, that you do what I suggested before: wrap the literal in strdup if required. That way you don 't incur the cost of allocating a copy all the time (just when necessary).


The problem is that "Hello World' is a const literal char array.

const char* conststr = "Hello World!";
char * string = strdup(conststr);

i assume the problem will be gone

Explanation: Compilers can allocate string literals in (readonly) data segment. The conversion to a char* (as opposed to const char*) is actually not valid. If you use use e.g.

gcc -Wall test.c

you'd get a warning.

Fun experiment:

Observe here that (because it is Undefined Behaviour) compilers can do funny stuff in such cases:

http://ideone.com/C39R6 shows that the program wouldn't 'crash' but silently fail to modify the string literal unless the string was copied.

YMMV. Use -Wall, use some kind of lint if you can, and do unit testing :){