I am learning C and am interested in the 'best-practice' approach to writing functions. Is it preferable to return a pointer to dynamically created memory, or populate a block of memory that has been statically allocated?
Please consider the functions allocatef
and populatef
as an example
char* allocatef(size_t size){
char* result = malloc(8*size);
// do other stuff
return result;
}
which we can interact with, through main
in the following way
int main(void){
char* data = allocatef(sizeof(int));
// do stuff
free(data);
}
As oppose to this approach, where the function expects the data to already be created
void populatef(char* data){
// do stuff
}
and the memory is statically allocated in main
, saving us from a potential memory leak. Perhaps one drawback is the caller is expected to know the exact type of input populatef
is expecting.
int main(void){
char data[8 * sizeof(int)];
populatef(data);
// no need to perform a destroy
}
I found some relevant questions here and here, but these concern C++ and performance considerations. I am more interested in memory safety, and the standard behavior among seasoned C programmers.