I have string " {"1":"[4,11,14,19,20,18,27]"} ". I want to change it into "{\"1\":\"4,11,14,19,20,18,27\"}".
Below is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *replace (char *this, char *withthat, char *inthis) {
char *where = inthis;
while ((where = strstr(where, this))) {
memcpy(where, withthat, strlen(withthat));
memmove(where+strlen(withthat),where+strlen(this), strlen(where+strlen(this))+1);
}
return inthis;
}
int main(void) {
char string[] = "{"1":"[4,11,14,19,20,18,27]"}";
printf("%s\n", replace(""", "\\\"", string));
printf("%s\n", replace("\"[" , "\"", string));
printf("%s\n", replace("]\\" , "\\", string));
printf("%s\n", replace("{" , "\"{", string));
printf("%s\n", replace("}" , "}\"", string));
return 0;
}
I get the error for the last two replace calls. My o/p is {\"1\":\"[4,11,14,19,20,18,27]\"} {\"1\":\"4,11,14,19,20,18,27]\"} {\"1\":\"4,11,14,19,20,18,27\"} Segmentation fault
I tried doing gdb, but not able to find the root cause of error. it is somehow concerned with memcopy, but not able to understand. If anyone can help me, it would be great. Thanks in advance.