简体   繁体   中英

String concatenation in C

char *str1 = malloc(256*sizeof(char));
char *str2 = "stack"
for (i=0;i<15;i++){
     sprintf(str1,"%s%s",str1,str2);
} 
printf("%s\n",str1);

I'm trying to concat str2 to str1 at each loop count. But this code segment works but vulnerable. Whats the best way to concat them?

According to the CERT Secure Coding Guidelines, you need to use pointers to const when referring to string literals .

So, char *str2 = "stack" needs to be const char *str2 = "stack"; .

This will make it immutable.

Additionally, you are using deprecated/obsolete functions . The secure function you should be using is strcat_s . For example,

Compliant Example

enum { BUFFERSIZE=256 };

void complain(const char *msg) {
  static const char prefix[] = "Error: ";
  static const char suffix[] = "\n";
  char buf[BUFFERSIZE];

  strcpy_s(buf, BUFFERSIZE, prefix);
  strcat_s(buf, BUFFERSIZE, msg);
  strcat_s(buf, BUFFERSIZE, suffix);
  fputs(buf, stderr);
}

Read here about strcpy_s() and strcat_s() .

The standard C function for string concatenation is char * strncat ( char * destination, char * source, size_t num ); .

If you want to use sprintf; something like this:

char *str1 = malloc(256*sizeof(char));
char *str2 = "stack";
*str1 = '\0';
for (i=0;i<15;i++){
    snprintf(str1 + strlen(str1), 256 - strlen(str1), "%s", str2);
} 
printf("%s\n",str1);

Use strncat :

char *str1 = malloc(256*sizeof(char));
str1[0] = '\0';
char *str2 = "stack"
for (i=0;i<15;i++){
     strncat(str1, str2, 256 - 1 - strlen(str2));
} 
printf("%s\n",str1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM