我正在连接几个字符串。运行程序时,它给我一个Debug Assertion失败!表达式的消息:(L“字符串不是空终止”&& 0)。
所有字符串似乎都以NULL结尾,但我不确定它还能是什么。有什么想法吗?
我在其中包含触发问题的代码摘录。
void foo(){
....
char adj_command_string[COMMAND_SIZE];
reconstructCommand(&command_parameters, adj_command_string);
....
}
void reconstructCommand(command* command_data, char* adjusted_string){
char partial_string[COMMAND_SIZE];
char string_rep[COMMAND_SIZE];
if (command_data->g_code.new_value){
sprintf_s(string_rep, COMMAND_SIZE, "G%d ", command_data->g_code.value);
strcat_s(partial_string, COMMAND_SIZE, string_rep);
}
// If position changed, include change in command.
if (command_data->pos.X.value){
sprintf_s(string_rep, COMMAND_SIZE, "X%.4f ", command_data->pos.X.value);
strcat_s(partial_string, COMMAND_SIZE, string_rep);
}
if (command_data->pos.Y.value){
sprintf_s(string_rep, COMMAND_SIZE, "Y%.4f ", command_data->pos.Y.value);
strcat_s(partial_string, COMMAND_SIZE, string_rep);
}
if (command_data->pos.Z.value){
sprintf_s(string_rep, COMMAND_SIZE, "Z%.4f ", command_data->pos.Z.value);
strcat_s(partial_string, COMMAND_SIZE, string_rep);
}
if (command_data->pos.A.value){
sprintf_s(string_rep, COMMAND_SIZE, "A%.4f ", command_data->pos.A.value);
strcat_s(partial_string, COMMAND_SIZE, string_rep);
}
// If Feedrate originally included, include it in modified command
if (command_data->feedrate.new_value){
sprintf_s(string_rep, COMMAND_SIZE, "F%.4f ", command_data->feedrate.value);
strcat_s(partial_string, COMMAND_SIZE, string_rep);
}
// If spindle speed originally included, include it in modified command
if (command_data->speed.new_value){
sprintf_s(string_rep, COMMAND_SIZE, "S%.4f ", command_data->speed.value);
strcat_s(partial_string, COMMAND_SIZE, string_rep);
}
adjusted_string = partial_string;
}
答案 0 :(得分:2)
您试图在字符串中放入比COMMAND_SIZE
允许的更多字符,不会为终止零留下空间。 COMMAND_SIZE
必须至少比字符串可以获得的最大长度大1,否则将无法终止字符串。
此外:
adjusted_string = partial_string;
这不符合你的想法。它将adjusted_string
的值更改为指向partial_string
,但之后它会通过返回丢弃该值。您可能希望strcpy_s
调用来复制结果。
答案 1 :(得分:1)
我不确定这是否是问题的根源,但是:
adjusted_string = partial_string;
不会将partial_string
的内容复制到adjusted_string
。使用strcpy()
或其他类似机制,确保adjusted_string
为空终止。
答案 2 :(得分:1)
似乎没有初始化partial_string
,它应该在将其用作strcat_s
的目标之前。
这样的事情应该在if
陈述之前:
partial_string[0] = '\0';
答案 3 :(得分:0)
进一步@Schwartz:确保始终以null结尾...
char partial_string[COMMAND_SIZE+1];
partial_string[COMMAND_SIZE] = '\0';