strlen这样判断有误么
时间: 2023-08-29 11:08:41 浏览: 70
在您的代码中,使用`strlen`函数来判断TCPCommand变量是否为空是有问题的。因为在每次调用`SetUpTCPtoSendInformation`函数时,TCPCommand变量可能已经被释放,而`strlen`函数仍然会返回之前分配的内存长度,导致判断结果不正确。
为了正确判断TCPCommand变量是否为空,您可以使用一个额外的标志变量来记录TCPCommand是否已经被设置。例如,您可以在`SetUpTCPtoSendInformation`函数外部声明一个名为`isTCPCommandSet`的静态变量,并在设置TCP命令时将其置为1,在获取TCP命令时检查该变量的值。这样就能准确地判断TCPCommand是否为空。
以下是修改后的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int SetUpTCPtoSendInformation(char option[], char *command) {
static char *TCPCommand;
static int isTCPCommandSet = 0;
if (strstr(option, "set")) {
TCPCommand = malloc(strlen(command) + 1);
if (TCPCommand == NULL) {
printf("Failed to set and obtain TCP command variable memory allocation\n");
return 0;
}
strcpy(TCPCommand, command);
isTCPCommandSet = 1;
return 1;
} else if (strstr(option, "get") && isTCPCommandSet) {
strcpy(command, TCPCommand);
free(TCPCommand);
isTCPCommandSet = 0;
return 1;
}
strcpy(command, "");
return 0;
}
int main() {
char a[32] = "zhngsan";
SetUpTCPtoSendInformation("set", a);
SetUpTCPtoSendInformation("get", a);
printf("%s\n", a);
SetUpTCPtoSendInformation("get", a);
printf("%s\n", a);
return 0;
}
```
在这个修改后的代码中,使用了`isTCPCommandSet`变量来记录TCPCommand是否已经被设置。在每次获取TCP命令时,会先检查`isTCPCommandSet`的值,只有在TCPCommand已经被设置时才进行复制操作,并进行相应的释放和重置操作。
这样,就能避免之前的问题,正确地判断TCPCommand是否为空。