使用g_malloc0后释放内存

时间:2021-10-12 21:19:32

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

我是c的新手,我试着适应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);
}

I don't know if the memory is been freed?

我不知道内存是否被释放了?

Many thanks for any suggestions.

非常感谢您的建议。

1 个解决方案

#1


1  

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.

free()类型为void,意思是您不能检查您的释放是否有效。释放一个未分配的地址将导致未定义的行为。例如,在Linux上,程序会崩溃。

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

因此,检查是否真的释放了所有东西的唯一方法就是使用内存调试器。Valgrind是个很好的例子

#1


1  

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.

free()类型为void,意思是您不能检查您的释放是否有效。释放一个未分配的地址将导致未定义的行为。例如,在Linux上,程序会崩溃。

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

因此,检查是否真的释放了所有东西的唯一方法就是使用内存调试器。Valgrind是个很好的例子