Marnix v. R.
Marnix v. R.

Reputation: 1698

c memory leak problem

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);

Upvotes: 0

Views: 266

Answers (2)

S..K
S..K

Reputation: 2024

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 :)

Upvotes: 2

peoro
peoro

Reputation: 26060

From the snippets you posted, there's no leak.

I think that with:

it seems that it doesn't completely free the memory

you mean that object still holds the old value.


In deleteMarnix, when you set objectPointer to NULL, you only set the value of the pointer in that function scope.

It doesn't set the value of the actual pointer object in the outer function.

To do that you can either:

  1. set it to NULL in the outer function

    Object *object = createObject(21.0f, 1.87f);
    deleteMarnix( object );
    object = NULL;
    
  2. pass a pointer to a pointer to your deleteMarnix function:

    void deleteMarnix(Object **objectPointer)
    {
      free(*objectPointer); //free the memory the pointer is pointing to
      *objectPointer = NULL; //stop it from becomming a dangling pointer
    }
    ...
    Object *object = createObject(21.0f, 1.87f);
    deleteMarnix( &object );
    

Upvotes: 3

Related Questions