简体   繁体   English

连接各种字符串时 strcat() 失败

[英]strcat() failing when concatenating various strings

I'm having trouble manipulating strings on C.我在处理 C 上的字符串时遇到问题。
I wrote this code to concatenate various values and run a python scrip from my C program.我编写这段代码来连接各种值并从我的 C 程序运行 python 脚本。

void python_print(float circle_1[3],float circle_2[3],float circle_3[3], 
      float x, float y){
  char run_this[200]="python3 beacons.py ";
  char circle_str_1[30],circle_str_2[30],circle_str_3[30],
          x_position[10],y_position[10];

  float *c1=&circle_1[0];
  float *c2=&circle_2[0];
  float *c3=&circle_3[0];

  sprintf(circle_str_1," %f %f %f", *c1,*(c1+1),*(c1+2));
  sprintf(circle_str_2," %f %f %f", *c2,*(c2+1),*(c2+2));
  sprintf(circle_str_3," %f %f %f", *c3,*(c3+1),*(c3+2));

  sprintf(x_position," %f",x);
  sprintf(y_position," %f",y);

  puts(circle_str_1);
  puts(circle_str_2);
  puts(circle_str_3);
  puts(x_position);
  puts(y_position);
  puts(run_this);

  strcat(run_this, circle_str_1);
  strcat(run_this, circle_str_2);
  strcat(run_this, circle_str_3);
  strcat(run_this, x_position);
  strcat(run_this, y_position);

  system(run_this);
}

For some reason circle_str_1 prints nothing, and the string I got a the end does not contain circle_str_1 and doubles the values for y_position.出于某种原因, circle_str_1什么都不打印,我得到的字符串结尾不包含circle_str_1并将 y_position 的值加倍。

circle_1={0.0,0.0,9.107}
circle_2={16.0,0.0,22.121}
circle_1={0.0,16.0,24.260}
y=-7.800317
x=-4.700037

This is what I get when I print the strings created.这是我打印创建的字符串时得到的。

Buffers are too small.缓冲区太小。

sprintf(x_position," %f",x); needs at least a buffer of 11. Printing into x_position[10] leads to undefined behavior .至少需要 11 的缓冲区。打印到x_position[10]会导致未定义的行为

1: Consider using snprintf() to avoid buffer overflow. 1:考虑使用snprintf()来避免缓冲区溢出。 2: use larger buffers. 2:使用更大的缓冲区。 3: Avoid "%f" format as it can quickly lead to outputs of hundreds of characters. 3:避免使用"%f"格式,因为它会很快导致数百个字符的输出。 Consider "%g"考虑"%g"

// char x_position[10],
// sprintf(x_position," %f",x);
char x_position[20];
int len = snprintf(x_position, sizeof x_position, " %g", x);
if (len < 0 || (unsigned) len >= sizeof x_position) {
  puts("Trouble printing");
  ...
} 

Do not use sprintf() , strcpy() , strcat() unless you have absolute certainly that overflow will not occur.不要使用sprintf()strcpy()strcat()除非你绝对确定不会发生溢出。


%f v. %g %f 诉 %g

printf("%%f <%f>\n", -DBL_MAX);
printf("%%g <%g>\n", -DBL_MAX);

Output Output

%f <-179769313486231570814527423731704356798070565449239578069709514447683386590106403234437238318580897337933920052621128987133479958537240295444402082043505598186819583097828779632178833278408753356733764414284292236482024122876814115690851853178733231033249466834451356736736928870307247739983885979597249860971.039805>
%g <-1.79769e+308>

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

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