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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With