从C函数返回的指针是好

从C函数返回的指针是好

本文介绍了从C函数返回的指针是好/坏的设计?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果从C函数返回指针是好/坏的设计?如果这是一个不好的做法,这将是在下面的例子中一个很好的做法:

I want to know if return pointer from a C function is good/bad design? If it is a bad practice, what would be a good practice in the following example:

问题是一个持续的一部分:

The question is a continued part of:c function return static variable

data.h 文件:

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

typedef struct
{
   int age;
   int number;
} person;

person * getPersonInfo();

data.c

#include "data.h"
static struct person* person_p = NULL;

person * getPersonInfo()
{
   person_p = (struct person*)malloc(10 * sizeof(struct person));
   return person_p;
}

的main.c

#include "data.h"

int main()
{
   person* pointer = getPersonInfo();
   return 0;
}

基本上,在文件中的功能需要得到阵列中的所有元素是价值静态指针指向 person_p ,如果它是不是一个好的做法,好的做法应该是又算得了什么?

basically, the main function in main file needs to get the value of all the elements of array which is pointed by static pointer person_p, if it is not a good practice, then what a good practice should be?

推荐答案

这是不好的唯一原因是因为你没有拥有它后面的任何内存管理结构。在当前的code,你有内存泄漏,因为你分配一个通过结构的malloc(),但不释放它。

The only reason it is bad is because you don't have any memory managing structure behind it. In your current code, you have a memory leak because you allocate a person struct via malloc() but do not free it.

考虑写你喜欢的,这样处理内存管理的包装函数:

Consider writing a wrapper function that handles that memory management for you like so:

void freePerson(struct person * personToDelete)
{
    free(personToDelete);
}

然后在你的主:

int main()
{
   person* pointer = getPersonInfo();
   freePerson(pointer); // After you are done using it
   return 0;
}

我也必须警惕铸造的malloc()的结果。在我的经验,它可以导致未定义的行为。

I also have to warn against casting the results of malloc(). In my experience it can result in undefined behavior.

这篇关于从C函数返回的指针是好/坏的设计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:32