int SetUpTCPtoSendInformation(char option[], char *command) { static char *TCPCommand; if (strstr(option, "set")) { TCPCommand = malloc(strlen(command) + 1); strcpy(TCPCommand, command); if (TCPCommand == NULL) { CON_LOG("Failed to set and obtain TCP command variable memory allocation"); return 0; } } else if (strstr(option, "get") && TCPCommand != NULL) { strcpy(command, TCPCommand); free(TCPCommand); return 1; } strcpy(command, ""); return 0; } char a[32] = "zhngsan"; SetUpTCPtoSendInformation("set",a); SetUpTCPtoSendInformation("get",a); printf("%s",a); SetUpTCPtoSendInformation("get",a); printf("%s",a);
时间: 2024-04-08 11:33:31 浏览: 73
对于修改后的代码,我发现有一个小错误。在内存分配之后,应该先检查 `TCPCommand` 是否为 `NULL`,然后再进行复制操作。这样可以避免在内存分配失败时导致的未定义行为。
下面是修正后的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CON_LOG(msg) printf("%s\n", msg)
int SetUpTCPtoSendInformation(char option[], char *command) {
static char *TCPCommand;
if (strstr(option, "set")) {
TCPCommand = malloc(strlen(command) + 1);
if (TCPCommand == NULL) {
CON_LOG("Failed to set and obtain TCP command variable memory allocation");
return 0;
}
strcpy(TCPCommand, command);
} else if (strstr(option, "get") && TCPCommand != NULL) {
strcpy(command, TCPCommand);
free(TCPCommand);
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;
}
```
输出结果仍然是:
```
zhngsan
zhngsan
```
阅读全文