[英]Valgrind Error - Split of a String C
我有一個程序,該程序讀取一個字符串並將其分為三個部分。 第一部分是操作碼,第二部分是數據,第三部分是鍵。
使用示例:
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()
分配的內存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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.