After looking online for a string replace function in C and finding so many examples that go through the entire string twice. First round to find how number of occurances of substitute in string, using that to malloc for a new string to include additional space for replace, then going through the search string again to get all but what's to be substituted out. I feel it's kind of silly to go through the string twice. Therefore, I'm trying to implement my own string replace, that only searches through the string for what's to be substituted, once.
Here is my code:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *strreplace(char * string, char * sub, char * replace);
int main(void){
char * mystring = "Here is my string.";
char * sub = " ";
char * replace = "__++";
char * newString = strreplace(mystring, sub, replace);
printf("new string: %s\n", newString);
return 0;
}
//my replace
char *strreplace(char *string, char *sub, char *replace)
{
if(!string || !sub || !replace) return NULL; // we need all inputs
char *result = (char*)malloc(1); // malloc memory for new string, will be realloc later
if(result == NULL){
printf("malloc returned null\n");
return NULL;
}
char *pos = string; // set pointer of pos to start of string
char *pos1; // pointer to search for sub
while((pos1 = strstr(pos, sub))) // search for sub and point to start of memory location
{
int len = (pos1 - pos); // length = found memory locatino - beginning of string
result = realloc(result, len + strlen(replace) + 1); // realloc result for string + replacemenet string + \0
strncat(result, pos, len); // pull up to this location
strcat(result, replace); //replace the found (strcat is fine because we already allocated the memory)
pos = (pos1 + strlen(sub)); // update pos to find next occurance of sub in string
}
// if we aren't at the end of the original string, we need to get what's left of original string
if(pos != (string + strlen(string)))
{
result = realloc(result, strlen(result) + strlen(pos) + 1); // realloc for what is left of original string
strcat(result, pos); // get the rest of the original string
}
return result; // return new string
}
Here is the same code, but with execution + some syntax highlighting: Ideone.com | Online C Compiler & Debugging Tool
It works great, until it gets to grabbing whatever remains in the search string after the last found sub. The realloc throws a runtime error:
Code:
*** glibc detected *** ./a.out: realloc(): invalid next size: 0x00011008 ***
Aborted
From my understanding, this is from me going outside of the bounds of the heap and using memory I haven't allocated, or using a free'd pointer. I'm not seeing where either of these are happening in my code, and was wondering what the best way to go about figuring out where the error exactly occurs.
Thank you for any input.