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
in data.h file:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int age;
int number;
} person;
person * getPersonInfo();
in 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;
}
in main.c
#include "data.h"
int main()
{
person* pointer = getPersonInfo();
return 0;
}
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?
It's not so much a "bad practice" (implying that it might cause problems) as much as it is a practice that will absolutely cause undefined behavior. It's like dereferencing a null pointer: don't do it and expect your program to behave within the limits of logic.
Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function.
The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.
You can return a structure from a function (or use the = operator) without any problems. It's a well-defined part of the language.
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);
}
Then in your main:
int main()
{
person* pointer = getPersonInfo();
freePerson(pointer); // After you are done using it
return 0;
}
I also have to warn against casting the results of malloc(). In my experience it can result in undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With