How to append a string in front of string in C

I have a string in C : "Phone/mis. ie Credit Card pmnt". Its length is 30 chars. I want to append a string in front of this "R*". So that my final output stands as "R* Phone/mis. ie Credit Card p". String truncates over here at the end as its max length is 30 chars. I have tried below code where iov_pPymArr->pymInfoArray[i].type_desc variable contains string "Phone/mis. ie Credit Card pmnt":

sprintf (iov_pPymArr->pymInfoArray[i].type_desc,"R*%s",iov_pPymArr->pymInfoArray[i].type_desc);

But it gives me output as : "R*R*e/mis. ie Credit Card pmnt". 

R* is getting appended twice and string is getting truncated from beginning instead of end. Please advice the possible Solution.


You cannot use sprintf in-place. The solution to your problem is to use a temporary buffer.

Using sprintf to write a buffer to itself is undefined behavior.

Use sprintf (or even better, snprintf) to write to another temporary buffer, and copy that to the actual buffer.

If you want to absolutely minimize your memory usage and your string buffer is large enough, you can use memmove to make space at the front of it (from the space past the null terminator which needs to be there unless you want a segfault) and then memcpy the prefix to the front, without the terminating zero.

#define STR " Phone/mis. ie Credit Card p"
#define PREFIX "R*"

#include <stdio.h>
#include <string.h>
int main(){
  char buff[sizeof(STR) + 2] = STR;
  memmove(buff + 2, buff, sizeof(buff) - 2);
  memcpy(buff, PREFIX, 2);


R* Phone/mis. ie Credit Card p

Note: Appending in the front is called prepending.

Writting a Buffer into itself using sprintf is undefined and not legal means of coding. Use strcat or a temporary buffer instead.

Need Your Help