user1840007
user1840007

Reputation: 675

Free memory after using g_malloc0

I am new to C. I am trying to get comfortable with malloc + free.

I have the following structure:

typedef struct {
    GstElement* pipeline;
    GFile* file;
    char* filename;
} Record;

I allocate some memory for the structure and assign some data to it:

Record* record_start (const char* filename)
{
    GstElement *pipeline;
    GFile* file;
    char* path;

    pipeline = gst_pipeline_new ("pipeline", NULL);

    /* Same code */

    path = g_strdup_printf ("%s.%s", filename, gm_audio_profile_get_extension (profile));
    file = g_file_new_for_path (path);

    Record *record = g_malloc0 (sizeof (Record));
    record->file = file;
    record->filename = path;
    record->pipeline = pipeline;

    return record;
}

Then I try to free all the memory allocated:

void record_stop (Record *record)
{
    g_assert(record);

    /* Same code */

    gst_object_unref (record->pipeline));
    g_clear_object (&record->file);
    g_free (record->filename);
    g_free (record);
}

Has the memory been freed?

Upvotes: 1

Views: 1652

Answers (1)

jocke-l
jocke-l

Reputation: 703

free() is of type void which means that you cannot check whether your freeing worked or not. Freeing a non-allocated address will result in undefined behavior. On Linux, for example, the program would crash.

So the only way to check if you really free'd everything is to use a memory debugger. Valgrind is a good one.

Upvotes: 1

Related Questions