Hi,
I need some help with this error, I simply can't find the cause. I know it is probably going to be obvious, but I'm fairly sure malloc is being used incorrectly.
Any and all comments welcome.
Valgrind Error:
Code:
==9316== 1 errors in context 1 of 6:
==9316== Invalid write of size 1
==9316== at 0x4C2839F: strcat (mc_replace_strmem.c:176)
==9316== by 0x400F6E: replace (stringfunctions.h:25)
==9316== by 0x402104: main (root.c:466)
==9316== Address 0x51b0069 is not stack'd, malloc'd or (recently) free'd
==9316==
==9316==
==9316== 1 errors in context 2 of 6:
==9316== Invalid read of size 1
==9316== at 0x4C28374: strcat (mc_replace_strmem.c:176)
==9316== by 0x400F6E: replace (stringfunctions.h:25)
==9316== by 0x402104: main (root.c:466)
==9316== Address 0x51b0059 is 0 bytes after a block of size 25 alloc'd
==9316== at 0x4C274A8: malloc (vg_replace_malloc.c:236)
==9316== by 0x400F03: replace (stringfunctions.h:20)
==9316== by 0x402104: main (root.c:466)
My Function:
Code:
LINE: 19 -> void replace(char *initial, char *startbreak, char *endbreak, char *insert){
LINE: 20 -> char *replacebuf;
LINE: 21 -> if ((replacebuf = malloc(strlen(initial) + strlen(insert))) == NULL)
LINE: 22 -> err(EX_OSERR, "data malloc");
LINE: 23 ->
LINE: 24 -> printf("%ld", startbreak - initial);
LINE: 25 -> strncpy(replacebuf, initial, (int)(startbreak - initial) - 1);
LINE: 26 -> strcat(replacebuf, insert);
LINE: 27 -> strcat(replacebuf, endbreak);
LINE: 28 -> strcpy(initial, replacebuf);
LINE: 29 -> free(replacebuf);
LINE: 30 -> }
Thanks!