Why can't I use printf format for replace a substring in a string?

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

Need Your Help

Editing JSON data from within a shopify liquid page

jquery json shopify

New to shopify and the liquid library, I have a customer who needs product pages to be a bit custom. One collection of items product page does not look similar to another.

#NAME error when setting cell formula through VBA.

excel vba excel-vba excel-formula

I am writing a macro that requires me to get the average of the values in a column with an unknown number of rows. I use this to get the number of the last row: