复制和释放 malloc 指针

标签 c pointers c99

我正试图追查内存泄漏并找到了一个来源。我在一个函数中 malloc'in 指针并在另一个函数中释放它,但我错过了理解如何复制指针指向的值同时也能够释放指针。

Current implementation (with memory leak):

// This code has been greatly simplified
// and as such does not appear to have any purpose
int foo(){
  int bestval = 0;
  char *best;
  char *match;
  for (int i=0;i<3;i++) {
      int returnValue = bar(&best);
      if (returnValue > 10) {
        (1)
         match = best;
      }
  }

  printf("%s", match); 
  (2)    
  return 0;
}


int bar(char ** best) {
  char*s = "Hello!";
  *best = malloc(strlen(s) + 1);
  strcpy(*best,s);
  return 0;
}

两个问题

  1. 如果我必须在 (1) 而不是 (2) 处释放内存,我该怎么做才能使匹配项仍然包含 best 中包含的内容?

  2. 我应该执行 strcpy 以复制最佳匹配吗?如果是这样,我是否必须在 foo 中执行另一个 malloc?

最佳答案

假设在 Foo 中有一个循环...有点摸不着头脑......

int foo()
{   
    int bestval = 0;   
    char *best;   
    char *match = 0;    // initialize to null

    // start some loop
    for (int i=0;i<3;i++) {       

        // fetch the next best value...
        int returnValue = bar(&best);       
        // some check (if best is really best!)
        if (returnValue > 10) {
            // if match has previously been populated, free it
            if(match) {
                free(match);
            }
            // save the new best value
            match = best;   
        }
        else {
           // not saving best in match, so free it!
           free(best);
        }
    }
    // end some loop

    // only do this if match was successful?!?
    if(match) {
        printf("%s", match);    
        // clean up once the best of the best has been used...
        free(match);
    }
    return 0; 
} 

关于复制和释放 malloc 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5618006/

相关文章:

c - 函数指针和函数由于参数不兼容

c++ - C++中指针的区别

c - 将数组传递给函数 vs 将变量传递给函数

c - `uint_fast32_t` 是否保证至少与 `int` 一样宽?

c - 将 'extern const' 替换为 'static const' 会影响性能吗?

c - BIO_do_connect 导致段错误

c - 德尔福指针类型转换

c - 这是限制指针的无效使用吗?

gcc - 如何使用 GCC 编译一个独立的环境?

c - 用openssl EVP在C中解密aes ccm 128,mic 8bit