0

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

使用示例:

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)

我不知道为什么会这样。谢谢。

4

1 回答 1

1

您应该通过in linefree()分配内存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
于 2013-10-31T14:13:33.813 回答