the function that just wont die, i mean work
i tried doing it diferently and playing with the code you guys gave me, but i still cant get it right myself.
any one see why this seg faults?
Code:
int replace(char *src, char search[], char replace[]) {
int search_length = strlen(search); /* String lengths to be used later for copying. */
int replace_length = strlen(replace);
int count = 0; /* Number of times spent looking for search. */
int time = 0; /* Number of replacements needed. */
char *value = NULL;
char *find; /* String position info. */
char *next_find;
char *spot = src;
while( (find = strstr(spot, search)) != NULL ) { /* Figure out how many replacements must be made. */
++count;
spot += search_length;
}
spot -= (search_length * count); /* Reset spot to orignal location. */
if(count > 0) {
while(time < count) {
find = strstr(spot, search); /* Find where the search is. */
next_find = strstr(spot + search_length, search); /* Find where to end the copy. */
realloc(value, find - spot + 1);
/* ***Problem start here*** */
strncat(value, spot, find - spot); /* Copy everything before search. */
realloc(value, replace_length + 1);
strcat(value, replace); /* Add the replacement text. */
spot += (replace_length + 1); /* Update spot's location. */
realloc(value, next_find - spot + 1);
strncat(value, spot, next_find - spot); /* Copy everything in between searches. */
}
}
strcpy(src, value); /* The long awaited lines... */
free(value);
return 0;
}