Suppose the following function:
float *dosomething(const float *src, const int N)
{
float *dst = (float *)malloc(sizeof(float) * N);
if(!dst)
{
printf("Cannot allocate memory\n");
exit(EXIT_FAILURE);
}
for(int i = 0; i < N; i++)
dst[i] = src[i] * 2;
return dst;
}
In this case we don’t need allocate memory previously if we want to use it right?
Now, just another case:
void dosomething(float *dst, const float *src, const int N)
{
for(int i = 0; i < N; i++)
dst[i] = src[i] * 2;
}
In the last case we need to allocate memory previously. So I share it and I’m wondering which is the best method for returning an array. Which of them provide more security to an user of the library or class? which method is most recommended? why?
What’s better practice or a better idea depends on what you’re actually trying to do.
A function like
char *strdup(const char *s)(POSIX) is implemented like the first case, it takes a string as an argument, allocates memory for another of the same length and then copies the source to the new piece of memory. It’s convenient and saves you from manually doing the common action of allocating a buffer for the copy of the string. You could assume this is simply like a call tomallocand thenstrcpy/memcpy.Then you’ve got a function like
char *strcpy(char *dest, const char *src), which is like the second case, where you have control of where the string is going to be copied to. This way you’re not forced into having the string copied into a dynamically allocated, not of your choice, piece of memory.The first way might come in handy if you needed to create and initialise some sort of dynamic structure (list, tree, etc), but then again the second way also suffices and gives you control of what piece of memory is being used; you can use dynamically allocated memory on the heap, or local variables on the stack, etc.
Personally, I would usually go the second way, because I have more control of what variable’s being initialised, and I’m not forced into having to use a newly
malloc‘d piece of memory (what if I wanted my local variable to be initialised?). You could always then write a wrapper function that makes a call tomallocand then to your function using the newly allocated memory as the destination.It’s really up to you and your design and what you’re trying to achieve, there are no right and wrong ways and as long as you remember the allocated memory you shouldn’t have any problems. I wouldn’t say either of the two is more “secure.”