Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free a pointer from an external function

Tags:

c

pointers

malloc

I wrote a program that uses a stack ADT.
The main creates a new stack while giving 3 functions to use from the user:

Stack my_stack = sCreate (copy_int, free_int, print_int);

when I call to a 'peek' function:

printf ("Peek: |%d|\n\n", *(int*)sPeek(my_stack));

I have a memory leak.

the peek function looks like this:

Element sPeek (Stack stack){
if ((NULL == stack) || (0 >= stack->used_places))
    return NULL;

Element returnElement = stack->copy_function(stack->stack_array[stack->used_places-1]);
if (NULL == returnElement){
    free (returnElement);
    return NULL;
}   
return returnElement;

It's caused probably by the copy_function called there, which is the copy_int that was given by the user:

Element copy_int (Element element){
int *new_int = (int*) malloc(sizeof(int*));
*new_int = *(int*)element;
if (NULL != new_int)
    return new_int;
else
    return NULL;

How do I release the pointer (malloc) from copy_int?

like image 233
Tango_Chaser Avatar asked Aug 21 '15 05:08

Tango_Chaser


People also ask

Can we free a pointer?

delete and free() in C++ In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer. It is an operator.

Can you free pointers in C?

The function free takes a pointer as parameter and deallocates the memory region pointed to by that pointer. The memory region passed to free must be previously allocated with calloc , malloc or realloc . If the pointer is NULL , no action is taken.

How do you free memory allocated in another function?

You only need the pointer which is pointing to the allocated memory to free it. Let's say that variable 'x' holds the address of allocated memory in fun1() then either you pass 'x' to fun2() or declare 'x' as global it doesn't matter but you must have that pointer to free the memory.

Can you use a pointer after freeing it?

Yes, when you use a free(px); call, it frees the memory that was malloc'd earlier and pointed to by px. The pointer itself, however, will continue to exist and will still have the same address.


1 Answers

Element e = sPeek(my_stack);
if (e) {
    printf ("Peek: |%d|\n\n", *(int*)e);
}
free(e);

Seems a bit obvious so not sure if that's what you meant.

like image 188
kaylum Avatar answered Oct 12 '22 23:10

kaylum