I'm trying to substitute/replace a substring in a larger string using printf family functions, but don't know why it doesn't work.
uint64_t end = 100000;
char *bigchar = "This is a try $TIME_ELAPSED to replace using sprintf";
char *pPos = strstr(bigchar, "$TIME_ELAPSED");
sprintf(pPos, " %7ld ms. ", end);
But I get a segmentation fault in sprintf line (fails the memcpy), Both, $TIME_ELAPSED and %7ld ms. has 13 char length.
Also, changing sprintf with this one gets a segmentation fault too.
sprintf(bigchar, "%.*s% 7ld ms. %s", (int)(pPos-bigchar), bigchar, end, pPos+13 );
pPos points to a location in the bigchar buffer, and this buffer is read-only because it contains string literal. In sprintf call you try to modify this read-only buffer.
char *s="Hai how are you!";
string literals always stores in a read only memory.
Any attempt to change that will give the segmentation fault.
s[4]='q'; // This gives seg fault
But you can do like this
char *bigchar = "This is a try $TIME_ELAPSED to replace using sprintf";
char temp[100];
strcpy(temp,bigchar );
char *pPos = strstr(temp, "$TIME_ELAPSED");
sprintf(pPos, " %7ld ms. ", end) can
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With