User avatar
ksharindam
Posts: 106
Joined: Sat Jan 09, 2016 4:16 pm

using dynamically loaded libraries causes segmentation fault

Sat Jun 15, 2019 4:15 pm

I am trying to use dynamically loaded libraries to get mp3 file duration.
But when I am trying to clean allocated memory. It causes segfault.

Code: Select all

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>

typedef void TagLib_File;
typedef void TagLib_AudioProperties;

TagLib_File* (*taglib_file_new)(char*);
int (*taglib_file_is_valid)(TagLib_File*);
TagLib_AudioProperties* (*taglib_file_audioproperties)(TagLib_File*);
int (*taglib_audioproperties_length)(TagLib_AudioProperties*);
void (*taglib_tag_free_strings)();
void (*taglib_file_free)(TagLib_File*);

int main()
{
    void* taglib = dlopen("libtag_c.so.0.0.0", RTLD_LAZY);
    taglib_file_new = dlsym(taglib, "taglib_file_new");
    taglib_file_audioproperties = dlsym(taglib, "taglib_file_audioproperties");
    taglib_audioproperties_length = dlsym(taglib, "taglib_audioproperties_length");
    // now use functions normally
    TagLib_File *TL_file = taglib_file_new( "/home/me/Music/Lilabali.mp3" );
    TagLib_AudioProperties *TL_props = taglib_file_audioproperties( TL_file );
    int length = taglib_audioproperties_length( TL_props );
    printf("%d\n", length);
    taglib_tag_free_strings(); // causes segfault
    taglib_file_free( TL_file ); // this also causes segfault
    dlclose(taglib);
}
Why it causes segfault?
EDIT:
But When I use Dynamically Linked library no segfault occurs.

Code: Select all

#include <stdlib.h>
#include <stdio.h>
#include <taglib/tag_c.h>

int main()
{
    TagLib_File *TL_file = taglib_file_new( "/home/me/Music/Lilabali.mp3" );
    TagLib_AudioProperties *TL_props = taglib_file_audioproperties( TL_file );
    int length = taglib_audioproperties_length( TL_props );
    printf("%d\n", length);
    taglib_tag_free_strings();  // no segfault
    taglib_file_free( TL_file );  // no segfault
    dlclose(taglib);
}
My Qt projects at ... https://github.com/ksharindam

User avatar
DougieLawson
Posts: 35364
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: using dynamically loaded libraries causes segmentation fault

Sat Jun 15, 2019 4:53 pm

You're missing the dlsym calls for the two functions that get the segfaults.

If you use RTLD_LAZY you have to register (with dlsym()) every function you want to use from the dynamically loaded library.
Note: Having anything remotely humorous in your signature is completely banned on this forum.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

User avatar
ksharindam
Posts: 106
Joined: Sat Jan 09, 2016 4:16 pm

Re: using dynamically loaded libraries causes segmentation fault

Sat Jun 15, 2019 5:26 pm

uff...what a silly mistake!
Problem solved.
Thanks.
My Qt projects at ... https://github.com/ksharindam

Return to “C/C++”