Memory allocation question
Hi. I have the following function which in the future will load all of the .so modules in a given directory with dlopen, for the moment it only lists the sub directories within "MODULES_PATH", and checks if these folders contain the mod_(module name).so file.
For ex. if in the ./modules folder this function finds a folder named "test", then it will search for a mod_test.so file in it.
Code:
int module_load()
{
DIR *dir = opendir(MODULES_PATH);
struct dirent *ent = NULL;
if (dir == NULL)
{
log_error("%s","Error loading modules!\n");
return -1;
}
char file_path[128];
file_path[0] = '\0';
while ((ent = readdir(dir)) != NULL)
{
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
sprintf(file_path, "%s%s/mod_%s.so", MODULES_PATH, ent->d_name, ent->d_name);
if (!fs_file_exists(file_path))
{
continue;
}
}
closedir(dir);
return 0;
}
My questions are the following:
1. Which would be the more natural way to declare the file_path variable? Like this:
Code:
char file_path[128];
(and automatically limit the file path`s length to 128 bytes) or like this:
Code:
char file_path[strlen(MODULES_PATH) + (strlen(ent->d_name) * 2) + 9];
and move the declaration inside the while loop. (the +9 at the end comes from the length of the strings "/mod_",".so", and the \0 character.). I tried and it works both ways, but I would like to know which is the standard way of doing it, and what would be the problem with one or the other solution.
2. It is more of a general question. If I understood correctly when a variable is declared statically (for ex: char variable[256]) the space for the variable is allocated before runtime, or when the execution enters a function. If this is true, shouldn`t the compiler throw an error at this:
Code:
char file_path[strlen(MODULES_PATH) + (strlen(ent->d_name) * 2) + 9];
because the size of the file_path variable depends on the length of the current file/folder name, and it is unknown at compile time?
Thank you.