0

Okay so I just want to know why my program keeps crashing, all im trying to do is loop through the pointer to a char array and replace the old character with the new one and return how many times I have replaced it:

int main(void) { 
   char *s = "hello";    
   printf("%lu\n",str_replace_all(s,'e','f')); 
   printf("%s",s); 
   return 0; 
} 

size_t str_replace_all(char *s,int oldc,int newc) { 
    size_t count = 0; 
    for(;*s != '\0'; s++) { 
       if(*s == oldc) { 
       *s = newc; 
        count++
    }
}
    return count; 
}

This compiles fine with gcc -ansi -W -Wall -pedantic but when i run it it crashes with this: Segmentation fault (core dumped) I need help figuring out whats going on, Thanks!

P.S expected output was hfllo

  • @Manish Mallavarapu Take into account that you have to declare the function before its call for example before main and include header stdio.h – Vlad from Moscow Jul 26 '15 at 08:03

2 Answers2

3

You're trying to modify a literal string, which produces undefined behavior. Change the declaration to:

char s[] = "hello";
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

The reason why you are getting a segmentation fault is that there is no memory allocated for the variable s. It is just a pointer pointing to some address location. Possible solution is char s[] = "hello" or you can allocate some memory in heap and memcpy or strcpy "hello" to the char pointer. Then you code will work. Hope it clears the concept. :)

Dipanjan
  • 181
  • 3
  • 12