简体   繁体   English

C中的字符串串联

[英]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. 我正在尝试在每次循环计数时将str2连接到str1。 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 . 根据CERT安全编码指南, 在引用字符串文字时 ,需要使用指向const的指针

So, char *str2 = "stack" needs to be const char *str2 = "stack"; 因此, char *str2 = "stack"需要为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 . 您应该使用的安全功能是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() . 在这里阅读有关strcpy_s()和strcat_s()的信息

The standard C function for string concatenation is char * strncat ( char * destination, char * source, size_t num ); 字符串连接的标准C函数是char * strncat ( char * destination, char * source, size_t num ); .

If you want to use sprintf; 如果要使用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 : 使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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