复制并释放 malloc 指针

发布于 2024-10-31 15:36:51 字数 794 浏览 6 评论 0原文

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

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)处释放内存,我该怎么做才能使匹配仍然具有最佳中包含的内容?

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

I'm trying to hunt down memory leaks and have found one source. I am malloc'in the pointer in one function and freeing it in another, but I'm missing out on understanding how to copy the value the pointer points to while also being able to free the pointer.

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

Two questions

  1. If I had to free memory at (1) rather than (2), how would I do it so that match would still have what was contained in best?

  2. Should I be doing strcpy to copy best to match? If so, do I have to do another malloc within foo?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

陈独秀 2024-11-07 15:36:51

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

A bit of a stab in the dark, assuming there's a loop in 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; 
} 
吝吻 2024-11-07 15:36:51

在功能栏中,strcpy 应该读作

strcpy(*best,s);

在主函数中,您可以通过

strcpy(match, best);
free(best);

匹配之前需要指向的有效内存块来复制最佳点的值。如果您进行

match = best;
free(best);

匹配也将无效,因为它指向最佳指向的同一释放内存。

In function bar the strcpy should read as

strcpy(*best,s);

In the main function you can copy the value best points to by

strcpy(match, best);
free(best);

match needs to point to a valid memory block before. If you do a

match = best;
free(best);

match will be invalid too because it points at the same freed memory best pointed.

沙沙粒小 2024-11-07 15:36:51

您需要知道字符串的大小。
在 (1) 处,您将分配已释放的内存地址的地址,您必须执行另一个 malloc 来 match*=malloc(sizestr) ,然后使用 memmove 或 strcpy 复制它,如果你想要自由最好。

如果我理解正确的话,你想将字符串复制到 best 中,然后释放 bests 内存并分配 ptr 来匹配?如果在 memmoving 或 strcpying 到另一个位置之前释放最佳内存,您会丢失其内容,并且如果您想首先将其复制到另一个位置,则需要在要将其复制到的位置分配内存,因此该代码上需要 2 个 malloc 。

You need to know the size of the string.
At (1) You would be assigning the address of a memory address that has already been freed, you have to do another malloc to match*=malloc(sizestr) and then copy it with memmove or strcpy if you want to free best.

If I understood properly, you want to copy the string into best, then free bests memory and assign ptr to match? if you free best memory before memmoving or strcpying to another location you lose its contents, and if you want to copy it to another location first you need to allocate the memory where you want to copy it to, so you need 2 mallocs on that code.

牵你手 2024-11-07 15:36:51

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

如果您在位置 (1)free,则无法执行此操作,因此 match 仍将包含 中包含的内容最好的。

我应该做 strcpy 来复制最佳匹配吗?如果是这样,我是否必须在 foo 中再进行一次 malloc?

  match = best;

通过上面的语句,两者都指向同一个位置。因此,根本不需要strcpy。为此,请为 match 分配内存以指向其长度为 best+1 的位置,然后执行 strcpy

If I had to free memory at (1) rather than (2), how would I do it so that match would still have what was contained in best?

If you free at position (1), it is not possible to do it so that match would still have what was contained in best.

Should I be doing strcpy to copy best to match? If so, do I have to do another malloc within foo?

  match = best;

With the above statement, both are pointing to the same location. So, there is no need to strcpy at all. To do that, allocate memory for match to point to whose length is best+1 and then do a strcpy.

故人如初 2024-11-07 15:36:51

复制指针的值不会复制底层内存。因此,在完成match之前不要free(best),否则您将需要malloc一个新的缓冲区,例如memcpy() 将内容从一个缓冲区传输到另一个缓冲区。

Copying the value of a pointer does not copy the underlying memory. So either, don't free(best) until you are done with match, or you will need to malloc a new buffer, and e.g. memcpy() the contents from one buffer to the other.

流年里的时光 2024-11-07 15:36:51

是的,您可以 mallocstrcpy

match = malloc(strlen(best) + 1);
strcpy(match, best);

但是,如果您的实现提供了它,您可以使用 strdup() 函数,这要容易得多:

match = strdup(best);

如果您还没有 strdup(),最好自己创建一个。

Yes, you can malloc and strcpy:

match = malloc(strlen(best) + 1);
strcpy(match, best);

But, if your implementation provides it you can use the strdup() function which is much easier:

match = strdup(best);

If you don't already have strdup(), it's a good idea to create one yourself.

星星的軌跡 2024-11-07 15:36:51

您当前的分配只是将指针分配给同一缓冲区。如果您随后 free() 这个缓冲区,您就删除了此处包含的内容(因此取消引用它是一个坏主意)。
您不需要使用 strcpy() 复制最佳匹配 - 您最好在 printf() (或它的最后一点)之后释放它。是需要的)。没有必要使用一个或六个额外的函数调用来使事情变得过于复杂,只需记住在每个函数末尾分配的free()内存即可!

Your current assignment simply assigns the pointers to the same buffer. If you then free() this buffer, you've removed what is contained here (and thus dereferencing it is a bad idea).
You don't need to use strcpy() to copy best to match - you'll be better off freeing it after the printf() (or the last point that it is needed). There's no point over-complicating things with an extra function call or six, just remember to free() memory that you've allocated at the end of each function!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文