[英]strcat() failing when concatenating various strings
我在处理 C 上的字符串时遇到问题。
我编写这段代码来连接各种值并从我的 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);
}
出于某种原因, 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
缓冲区太小。
sprintf(x_position," %f",x);
至少需要 11 的缓冲区。打印到x_position[10]
会导致未定义的行为。
1:考虑使用snprintf()
来避免缓冲区溢出。 2:使用更大的缓冲区。 3:避免使用"%f"
格式,因为它会很快导致数百个字符的输出。 考虑"%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");
...
}
不要使用sprintf()
、 strcpy()
、 strcat()
除非你绝对确定不会发生溢出。
%f 诉 %g
printf("%%f <%f>\n", -DBL_MAX);
printf("%%g <%g>\n", -DBL_MAX);
Output
%f <-179769313486231570814527423731704356798070565449239578069709514447683386590106403234437238318580897337933920052621128987133479958537240295444402082043505598186819583097828779632178833278408753356733764414284292236482024122876814115690851853178733231033249466834451356736736928870307247739983885979597249860971.039805>
%g <-1.79769e+308>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.