Free allocated memory before return a function

回眸只為那壹抹淺笑 提交于 2019-11-30 12:43:02

As the memory allocated by malloc() is on the heap and not on the stack, you can access it regardless of which function you are in. If you want to pass around malloc()'ed memory, you have no other option than freeing it from the caller. (in reference counting terms, that's what is called an ownership transfer.)

1) Yes, you can free() the malloc'ed memory outside the function

2) No, you cannot free it inside the function and have the data passed outside the function, so you must do 1) here

3) If you're concerned about scarce memory, you need to check for failure from memory allocations always, which you fail to do here, which is then likely to lead to a segfault

Ofcourse you can free the memory allocated in a function outside of that function provided you return it.

But, an alternative would be to modify your function like below, where the caller only allocates & frees the memory. This will be inline with concept of the function which allocates the memory takes responsibility for freeing the memory.

void queueBulkDequeue(queueADT queue, char *pElements, unsigned int size) 
{     
   unsigned int i;     
   for (i=0; i<size; i++)     
   {         
      *(pElements+i) = queueDequeue(queue);     
   }     
   return; 
} 

//In the caller

char *pElements = malloc(size * sizeof(char));
queueBulkDequeue(queue, pElements, size);
//Use pElements
free(pElements);

Yes, you can free memory allocated in a function that you call outside the function; this is precisely what you need to do in this case.

Alternatives include passing a buffer and its length into the function, and returning the actual length to the caller, the way fgets does. This may not be the best alternative, because the callers would need to call your function in a loop.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!