gpt4 book ai didi

c - Valgrind 错误 - 字符串 C 的分割

转载 作者:行者123 更新时间:2023-11-30 15:43:48 25 4
gpt4 key购买 nike

我有一个程序,它读取一个字符串并将其分成三部分。第一部分是操作码,第二部分是数据,第三部分是 key 。

使用示例:

put this is stackoverflow

opcode: put
data: this is
key: stackoverflow

主要代码:

 int main(int argc, char **argv){
char command[MAX_MSG];
fgets(command, sizeof(command), stdin);
command[strcspn (command, "\n")] = '\0';
char *aux_command = strdup(command);
char *opcode = strtok(command, " ");
int success = 0;
char *key ;
char *data;
if(strcmp(opcode, "put") == 0){
key = getKey(strdup(aux_command), opcode);
if(key == NULL){
printf("Invalid number of arguments.\n");
success = -1;
}

else{
data = getData(aux_command, opcode, key);

}
}
printf("opcode: %s\n",opcode);
printf("data: %s\n",data);
printf("key: %s\n",key);
free(aux_command);

}

我的问题是当我使用 valgrind 运行程序时它给出了这个结果:

==2663==    by 0x4EBD971: strdup (strdup.c:42)
...
==2663== definitely lost: 12 bytes in 1 blocks
==2663== indirectly lost: 0 bytes in 0 blocks
==2663== possibly lost: 0 bytes in 0 blocks
==2663== still reachable: 0 bytes in 0 blocks
==2663== suppressed: 0 bytes in 0 blocks
==2663==
==2663== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)

我不知道为什么会发生这种情况。谢谢。

最佳答案

您应该在行中free()strdup()分配的内存

key = getKey(strdup(aux_command), opcode);

它分配的内存没有被释放,因此 valgrind 将其显示为内存丢失。

建议的代码是:

...
char *command =NULL; //declare variable
char *key ;
char *data;
if(strcmp(opcode, "put") == 0){
command = strdup(aux_command); //use variable to store new memory
key = getKey(command, opcode);
if(key == NULL){
printf("Invalid number of arguments.\n");
success = -1;
}

else{
data = getData(aux_command, opcode, key);

}
}
printf("opcode: %s\n",opcode);
printf("data: %s\n",data);
printf("key: %s\n",key);
free(aux_command);
free(command); //free it when done

关于c - Valgrind 错误 - 字符串 C 的分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19708735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com