在C编程和使用malloc时,返回指针的指针函数中的free()在哪里?

在C编程和使用malloc时,返回指针的指针函数中的free()在哪里?,c,malloc,function-pointers,free,C,Malloc,Function Pointers,Free,我创建了一个返回指针的指针函数。我在函数中放置了一个malloc,但是,我不知道是否要将free()放在函数中,如果是这样的话,它是必须放在函数中还是放在main中,当您确信已经使用完分配的指针时,通常会调用free。指示返回值是否应为自由值也是一种很好的做法。下面是用C语言组织方法的一个示例: int main() { //let's start our method with initializing any declarations int mystringlen = 25;

我创建了一个返回指针的指针函数。我在函数中放置了一个
malloc
,但是,我不知道是否要将
free()
放在函数中,如果是这样的话,它是必须放在函数中还是放在
main

中,当您确信已经使用完分配的指针时,通常会调用free。指示返回值是否应为自由值也是一种很好的做法。下面是用C语言组织方法的一个示例:

int main() {
  //let's start our method with initializing any declarations
  int mystringlen = 25;
  char* mystring1 = NULL;
  char* mystring2 = NULL;

  //let's now assign some data
  mystring1 = malloc(mystringlen * sizeof(char));  
  if (mystring1 == NULL) goto end; //malloc failure :(
  strncpy(mystring1, "Hello world", mystringlen);

  //strdup(3) mallocs its return value, we should be careful and check
  //documentation for such occurances
  mystring2 = strdup("hello world");
  if (mystring2 == NULL) goto end; //malloc failure


  //let's do our processing next
  printf("%s\n%s\n", mystring1, mystring2);


  //let's do our cleanup now
  end:
    if (mystring1) free(mystring1);
    if (mystring2) free(mystring2);
    return 0;
}

有一些可用的约定,有些可能反对使用goto进行流控制。请注意,我们将指针设置为
NULL
,以便稍后进行安全清理。我们也在检查malloc故障,这是一个很好的做法。

当您不需要分配的内存时,您可以释放它。请参见此

#include <stdio.h>
#include <stdlib.h>


int *fun()
{
     int *ptr=malloc(sizeof(int));

     if(ptr==NULL)
     {
         printf("Error");
         exit(1);
     }

     return ptr;
}

int main()
{
     int*ptr=fun();

     /*do something*/

     /*After all work of ptr is done*/
     free(ptr);

     /*do something*/
}
#包括
#包括
int*fun()
{
int*ptr=malloc(sizeof(int));
如果(ptr==NULL)
{
printf(“错误”);
出口(1);
}
返回ptr;
}
int main()
{
int*ptr=fun();
/*做点什么*/
/*ptr的所有工作完成后*/
免费(ptr);
/*做点什么*/
}

如果您不需要释放分配的内存,它可以在任何地方释放,只要在函数上方的注释中注明调用者负责释放返回。