Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

replace

printf

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 );
like image 252
user3411085 Avatar asked May 01 '26 07:05

user3411085


2 Answers

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.

like image 109
Wojtek Surowka Avatar answered May 02 '26 21:05

Wojtek Surowka


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
like image 30
VINOTH ENERGETIC Avatar answered May 02 '26 22:05

VINOTH ENERGETIC