Jojo.Kimic Jojo.Kimic - 1 year ago 65
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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download