I ran my program through valgrind, and saw the errors about the memory corruption. I`ve also corrected some other errors too, but there are two more errors left, and I can`t figure out what am I doing wrong. This is the modified function:
Code:
typedef struct
{
char *name;
void *handle;
} module_t;
int module_load()
{
DIR *dir = opendir(MODULES_PATH);
struct dirent *ent = NULL;
void *module_handle = NULL;
void (*module_init)() = NULL;
if (dir == NULL)
{
log_error("%s","Error loading modules!\n");
return -1;
}
char file_path[256];
while ((ent = readdir(dir)) != NULL)
{
module_t *module = NULL;
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
sprintf(file_path, "%s%s/%s%s.so", MODULES_PATH, ent->d_name, MODULES_PREFIX, ent->d_name);
if (!fs_file_exists(file_path))
{
log_error("%s%s%s","Error loading mod_", ent->d_name, ".so. No such file!\n");
continue;
}
module_handle = dlopen(file_path, RTLD_LAZY);
if (module_handle == NULL)
{
log_error("%s%s%s","Error loading mod_", ent->d_name, ".so. Invalid module!\n");
continue;
}
module_init = dlsym(module_handle, "init");
if (module_init == NULL)
{
log_error("%s%s%s","Module mod_", ent->d_name, ".so doesn`t have a init function. Ignoring...!\n");
dlclose(module_handle);
continue;
}
log_message("%s%s\n","Loading module: mod_", ent->d_name);
module_init();
module = malloc(sizeof(module_t *));
module->name = malloc(strlen(ent->d_name) + strlen(MODULES_PREFIX) + 1);
module->handle = module_handle;
num_modules++;
if (modules == NULL)
{
modules = malloc(sizeof(module_t *));
}
else
{
modules = realloc(modules, num_modules * sizeof(module_t *));
}
modules[num_modules-1] = module;
}
closedir(dir);
return 0;
}
Valgrind is showing the following two errors:
1. Invalid write of size 4
2. Address 0x402669c is 0 bytes after a block of size 4 alloc'd
I figured out, that there is some kind of problem with this line:
Code:
module->handle = module_handle;
. If I remove it, both errors go away, but to be honest, I can`t figure out what is the problem. module->handle is a void pointer, dlopen also returns a pointer casted to void, and all I`m saying is that the first pointer is equal to the second.
If you need more information, please let me know.
Thank you.