i have c function in my project which creates a struct and returns the pointer.
typedef struct object
{
float var1;
float var2;
}
Object;
Object *createObject(float newVar1, float newVar2)
{
Object *object; //create new structure
object = (Object*)malloc(sizeof(Object)); //malloc size for struct object
if(object != NULL) //is memory is malloc'd
{
object->var1 = newVar1; //set the data for var1
object->var2 = newVar2; //set the data for var2
return object; //return the pointer to the struct
}
return NULL; //if malloc fails, return NULL
}
now the struct gets used and after a while i want to delete this structure, i made this function:
void deleteMarnix(Object *objectPointer)
{
free(objectPointer); //free the memory the pointer is pointing to
objectPointer = NULL; //stop it from becomming a dangling pointer
}
this last code snippet shows how i make an object, use it and try to delete it, however, it seems that it doesn’t completely free the memory. what am i doing wrong?
Object *object = createObject(21.0f, 1.87f);
//do things here with object.
deleteMarnix(object);
What free() does is not free the memory held by the pointer completely, but actually makes it available for later use if we call a malloc after calling free().
An evidence to this is you will be able to access the memory location after calling free and before setting the pointer to NULL ( assuming you haven’t already called malloc() ). Of course the values will be reset to some default values. ( On some compilers i found int was set to 0 ).
Although there is no memory leak, this might answer your question.
Let us know 🙂