[英]Valgrind Error - Split of a String C
I have this program that reads a string and splits it in three parts. 我有一个程序,该程序读取一个字符串并将其分为三个部分。 The first part is opcode, the second is data and the third is key.
第一部分是操作码,第二部分是数据,第三部分是键。
Example of use: 使用示例:
put this is stackoverflow
opcode: put
data: this is
key: stackoverflow
Code Main: 代码主要:
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);
}
My problem is when I run my program with valgrind
it gives this result: 我的问题是,当我使用
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)
I don't know why this is happening. 我不知道为什么会这样。 Thanks.
谢谢。
You should free()
memory allocated by strdup()
in line 您应该
free()
strdup()
分配的内存strdup()
行
key = getKey(strdup(aux_command), opcode);
The memory allocated by it is not getting freed and hence valgrind is showing it as memory lost. 由它分配的内存没有被释放,因此valgrind将其显示为内存丢失。
Suggested code is: 建议的代码是:
...
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.