我创建了一个返回指针的指针函数。我在函数内放置了malloc
,但是然后,我不知道是否要放置free()
,如果要放置,是否必须将其放入函数或main
中。
您不需要时释放已分配的内存,请参阅此
#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*/
}
通常,当您确信已完成使用分配的指针时,可以免费拨打电话。指示是否应释放返回的值也是一种好习惯。这是在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失败,这是一个好习惯。