Jojo.Kimic Jojo.Kimic - 1 month ago 11
C Question

BOOLEAN allocate_items(struct item * items, size_t howmany) function for allocate an array of struct item

Recently, I'm learning C. I found a question on the internet. The question is:


What is the problem with this function in terms of memory allocation?
What is a good solution? You may assume that a struct item type has
been declared. The purpose of this function is to allocate an array of
struct item, which you may assume has been declared prior to this
function.

BOOLEAN allocate_items(struct item * items, size_t howmany)
{
size_t count;
items = malloc(sizeof(struct item) * howmany);

if(!items) {
perror("failed to allocate memory");
return FALSE;
}
return TRUE;

}



So, I think that the 4th line is wrong. It should be like:

items = malloc(sizeof(struct item));


And also the 6th line is wrong. It should be like:

if(items == NULL){


Is it correct?

Answer

First of all, both line 4 and 6, as you mentioned seems to be OK.

That said, the basic problem with this function is, you're allocating memory to a local scope of variable. This way

  • as you don't return the pointer to allocated memory, after the function returns, there would be no way to access the allocated memory.
  • by not freeing up the allocated memory, you will face memory leak.

If you have to allocate memory to a pointer, you need to pass the address of that pointer to the function and allocate memory. You can also return the pointer but then you need to change the function signature.

Finally, arrays are not pointers and vice-versa. They may appear or beahave similar sometimes, but they are not the same.

Comments