1

I'm trying to build a function in C that changes the characters 'f' and/or 'o' of a string to 'x'. For some reason I keep getting a segmentation fault (core dumped) when i run the program, even though it compiles without issue. I understand that a segmentation fault occurs when the program tries to access a location in memory that it doesn't have access to, however, I don't see what in my code could be causing this issue. here's my code:

#include <stdio.h>

void censor(char p[]);

int main(){


    censor("foodfool");
    return 0;
}

void censor(char p[]){

    int i;
    for(i = 0;p[i] != '\0';i++){
        if(p[i] == 'f' || p[i] == 'o')
            p[i] = 'x';
        printf("%c", p[i]);     

    }

    printf("\n");
}
Kijewski
  • 25,517
  • 12
  • 101
  • 143
Raw_Data
  • 19
  • 2
  • You are using an environment that doesn't permit you to modify string literals. Change your program to read strings from stdin, using `fgets`, and it will work. – zwol Jun 30 '17 at 00:31
  • 2
    Replace `censor("foodfool");` with `char s[] = "foodfool"; censor(s);` – r3mainer Jun 30 '17 at 00:33
  • I wonder why it wasn't a type error. "cannot convert const char * to char *" or something like that – Maya Jun 30 '17 at 00:37
  • @NieDzejkob It would have been in C++, and some compilers can make it be one in C as well (e.g. gcc/clang's `-Wwrite-strings` option does exactly this). It's an intentional backward compatiblity wart in the standard. I highly recommend using `-Wwrite-strings` or equivalent for new code, but turning it on for old code can be months of work for very little gain. – zwol Jun 30 '17 at 01:21
  • @zwol I highly recommend using `-Wall -Wextra` and for production, `-Werror`. – Maya Jun 30 '17 at 09:21
  • @NieDzejkob Those are good _also_, but none of them turns on `-Wwrite-strings`. – zwol Jun 30 '17 at 11:39
  • Seconding compiling with `-Wall` – Alex Reynolds Jul 01 '17 at 21:17

1 Answers1

2

The string "foodfool" is a compile-time constant, which you cannot modify. Replace it with a char array (char[]) or heap-allocated char pointer (char*).

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345