C: string replace in loop (c beginner) -
i need replace strings in text. found function here @ stackoverflow:
char *replace(const char *s, const char *old, const char *new) { char *ret; int i, count = 0; size_t newlen = strlen(new); size_t oldlen = strlen(old); (i = 0; s[i] != '\0'; i++) { if (strstr(&s[i], old) == &s[i]) { count++; += oldlen - 1; } } ret = malloc(i + count * (newlen - oldlen)); if (ret == null) exit(exit_failure); = 0; while (*s) { if (strstr(s, old) == s) { strcpy(&ret[i], new); += newlen; s += oldlen; } else ret[i++] = *s++; } ret[i] = '\0'; return ret; }
this function works me fine single replacement. need replace whole array "str2rep" "replacement". i'm trying do(im beginner)
**** #define maxtext 39016 int l; int j; char *newsms = null; char text[maxtext]; char *str2rep[] = {":q:",":n:"}; char *replacement[] = {"?","\n"}; strcpy((char *)text,(char *)argv[5]); l = sizeof(str2rep) / sizeof(*str2rep); for(j = 0; j < l; j++) { newsms = replace(text,(char *)str2rep[j],(char *)replacement[j]); strcpy(text,newsms); free(newsms); } textlen = strlen(text);
this code works locally, if build single file... asterisk module, when being executed, asterisk stops with:
* glibc detected * /usr/sbin/asterisk: double free or corruption (!prev): 0x00007fa720006310 *
issues:
ret = malloc(i + count * (newlen - oldlen));
small. need + 1.
consider happensreplace("", "", "")
. if ref this, wrong too.questionable results mixing signed/unsigned.
count
signed.newlen, oldlen
unsigned.
think original code works ok, not using wrap-around nature of unsigned math when can avoided happens whennewlen < oldlen
.// + count * (newlen - oldlen) size_t newsize = + 1; // + 1 above reason if (newlen > oldlen) newsize += count * (newlen - oldlen); if (newlen < oldlen) newsize -= count * (oldlen - newlen); ret = malloc(newsize);
insure enough space. @hyde various approaches available here.
// strcpy(text, newsms); if (strlen(newsms) >= sizeof text) handle_error(); strcpy(text, newsms);
minor
no need casts
// newsms = replace(text, (char *) str2rep[j], (char *) replacement[j]); newsms = replace(text, str2rep[j], replacement[j]);
better use
size_t
i
. pedantic solution usesize_t count
.// int i; size_t i;
Comments
Post a Comment