繁体   English   中英

标记字符串时的内存泄漏

[英]Memory Leaks when Tokenizing a String

我用 C 编写了一个程序来标记输入字符串,当用户输入“exit”时,它退出程序。

它正确地标记了字符串,但是,当我使用 valgrind 测试我的程序时,出现了一些内存泄漏。 唯一没有发生内存泄漏的情况是在编译然后执行之后,我立即退出。

这是 valgrind 的输出: Valgrind Memory Leaks

这是我的程序代码:

    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; 
}

导致 valgrind 内存泄漏的问题可能是什么? 我正在为我的输入字符串释放内存,但我仍然遇到内存泄漏。

savecpy应该被释放。 手册中所示

新字符串的内存通过 malloc(3) 获得,并且可以通过 free(3) 释放。

savecpy在通过strtok_r第三个参数后不能被释放,因为这个函数修改了指针。 而是通过这样的事情

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

然后你可以免费savecpy

暂无
暂无

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

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