简体   繁体   English

标记字符串时的内存泄漏

[英]Memory Leaks when Tokenizing a String

I wrote a program in C that tokenizes an input string, and when the user enters "exit", it exits the program.我用 C 编写了一个程序来标记输入字符串,当用户输入“exit”时,它退出程序。

It tokenizes the string correctly, however, when I test my program with valgrind, I get some memory leaks.它正确地标记了字符串,但是,当我使用 valgrind 测试我的程序时,出现了一些内存泄漏。 The only scenario when I don't get memory leaks is after compiling and then executing, I exit right away.唯一没有发生内存泄漏的情况是在编译然后执行之后,我立即退出。

Here is the output with valgrind: Valgrind Memory Leaks这是 valgrind 的输出: Valgrind Memory Leaks

And here is my code for the program:这是我的程序代码:

    int main() {
       /* Main Function Variables */
       char *buf;
       char *savecpy = NULL;
       char *token;
       size_t num_chars;
       size_t bufsize = 2048;
       int run = 1;
       int tok_count = 0;
       int cmp;

       /* Allocate memory for the input buffer. */
       buf = (char *) malloc(sizeof(char) * bufsize);

       /*main run loop*/
       while(run) {
           /* Print >>> then get the input string */
           printf(">>> ");
           num_chars = getline(&buf, &bufsize, stdin);

           cmp = strcmp(buf, "exit\n");

           if (num_chars > 1) {
               /* Tokenize the input string */
               if (cmp != 0) {
                  /* Display each token */
                  savecpy = strdup(buf);
                  while((token = strtok_r(savecpy, " ", &savecpy))) {
                        printf("T%d: %s\n", tok_count, token);
                        tok_count++;
                    }
               }
               /* If the user entered <exit> then exit the loop */
               else {
                 run = 0;
                 break;
               }
         }
         tok_count = 0;
       }

    /*Free the allocated memory*/
    free(buf);
    return 1; 
}

What may be the problem here that is causing the memory leaks in valgrind?导致 valgrind 内存泄漏的问题可能是什么? I am freeing my memory for my input string, but I still get memory leaks.我正在为我的输入字符串释放内存,但我仍然遇到内存泄漏。

savecpy should be freed. savecpy应该被释放。 As seen in the manual :手册中所示

Memory for the new string is obtained with malloc(3), and can be freed with free(3).新字符串的内存通过 malloc(3) 获得,并且可以通过 free(3) 释放。

savecpy can not be freed after passing through strtok_r third argument, as this function modifies the pointer. savecpy在通过strtok_r第三个参数后不能被释放,因为这个函数修改了指针。 Rather pass something like this而是通过这样的事情

char* ptr;
strtok_r(..,.., &ptr);

Then you can free savecpy然后你可以免费savecpy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM