Valgrind错误-字符串C的拆分
我有一个程序,它读取一个字符串并将其分成三部分。第一部分是操作码,第二部分是数据,第三部分是键 使用示例:Valgrind错误-字符串C的拆分,c,malloc,free,C,Malloc,Free,我有一个程序,它读取一个字符串并将其分成三部分。第一部分是操作码,第二部分是数据,第三部分是键 使用示例: 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);
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);
}
我的问题是,当我运行程序时,它会给出以下结果:
==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)
我不知道为什么会这样。谢谢。您应该释放()
由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
在这里使用
memmove肯定不是一件好事:当源和目标重叠时不能使用它,因为这里就是这种情况。为什么不在空格上strok命令字符串,使用第一个标记作为操作码,最后一个作为键,并用空格连接所有中间标记以重建数据?@Bentoy13 memmove的存在完全是为了处理重叠内存:。@Bentoy13:这对于memmove和重叠内存是不正确的memmove
专门定义为允许源/目标重叠。我的错,我完全把memcpy搞糊涂了。感谢您显示我的错误。“建议的代码”还将受益于检查strdup
是否返回空值实际上,空值的检查必须直接在strdup之后进行。@Shahbaz,同意,但是代码不是完整的代码检查,而是关于问题的建议。