简体   繁体   中英

In C programming and using malloc, where is the free() in a pointer function that returns a pointer?

I have created a pointer function that returns a pointer. I place a malloc inside the function but then, I don't know whether to put the free() and if so, if it has to go in the function or in main .

You free allocated memory when you don't need it see this

#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*/
}

You typically call free when you are confident that you have finished using the allocated pointer. It's also a good practice to indicate whether returned values should be free'd or not. Here's one example of organizing a method in 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;
}

There's a few conventions available and some may object to using goto for flow control. Note that we set our pointers to NULL so that we can later do safe cleanup. We're also checking for malloc failures which is a good practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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