There are a lot of find/replace functions available on the internet, but i can't find why this is not working...( my own solution ) Here is what i tried
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* strrpl(char *str, char* find, char *replace)
{
int i;
char *pt = strstr(str, find), *firstStr;
firstStr = (char* )malloc(100 * sizeof(char));
// copy just until i find what i need to replace
// i tried to specify the length of firstStr just with pt - str
strncpy(firstStr, str, strlen(str) - strlen(pt));
strcat(firstStr, replace);
strcat(firstStr, pt + strlen(find));
for(i = 0; i < strlen(firstStr); i++)
str[i] = firstStr[i];
return str;
}
int main()
{
char *s, *s1, *s2;
s = (char* )malloc(100 * sizeof(char));
s1 = (char* )malloc(100 * sizeof(char));
s2 = (char* )malloc(100 * sizeof(char));
scanf("%s", s1);
scanf("%s", s2);
scanf("%s", s);
printf("%s", strrpl(s, s1, s2));
return 0;
}
The compilation gives me the error "segmentation fault" but i can't figure what memmory is he trying to alloc and he can't. I overrided a memory block or something? Please help :)
Thanks
malloc()returningNULL(which you don't check for!). The fault means you overwrote valid memory, i.e. you have a bug. Run the program in a debugger, and/or Valgrind if available.strlenin aforloop like that, it is expensive. You should instead store the value in a variable and use that.for-loop at all for such a simple task,memcpyis there for you. And this is also where you have at least one bug, you don't terminatestrwith a0byte.' '(space character), and if thefindstring is in the middle, it will always returnNULL, so i usedgets()to read my strings