 |
forums.ps2dev.org Homebrew PS2, PSP & PS3 Development Discussions
|
| View previous topic :: View next topic |
| Author |
Message |
kouky

Joined: 25 Sep 2007 Posts: 48 Location: London
|
Posted: Sat Sep 20, 2008 9:08 am Post subject: memory leak on read directory example? |
|
|
I'm chasing a memory leak in my homebrew project...
I'm using this read directory code from the ogg player example...
| Code: |
filenames_t* readDirectory (char* directory) {
int ret=-1;
int n_dir=0;
int n_reg=0;
fio_dirent_t record;
char** filename_array =NULL;
int i =0;
filenames_t* current_dir =NULL;
int* fileattrib_array =NULL;
/*Create space */
current_dir = malloc(sizeof(*current_dir));
filename_array = malloc(sizeof(char*)*FILEARRAYBUFFER);
fileattrib_array = malloc(sizeof(int)*FILEARRAYBUFFER);
/*Open Directory */
if ((ret = fioDopen(directory)) < 0) {
//printf("Error opening dir\n");
return NULL;
}
i=0;
n_dir=0;
n_reg=0;
while (fioDread(ret, &record) > 0) {
/*Expand array if too small */
if (i % FILEARRAYBUFFER == 0) {
filename_array = realloc(filename_array,
sizeof(char*) * (i+FILEARRAYBUFFER));
fileattrib_array = realloc(fileattrib_array,
sizeof(int) * (i+FILEARRAYBUFFER));
}
/*Copy filename into array */
filename_array[i] = malloc(strlen(record.name)+1);
strcpy(filename_array[i], record.name);
fileattrib_array[i] = record.stat.mode;
/*Keep track of number of files */
if (FIO_SO_ISDIR(record.stat.mode)) {
n_dir++;
}
if (FIO_SO_ISREG(record.stat.mode)) {
n_reg++;
}
i++;
}
if (ret >= 0) fioDclose(ret);
current_dir->filenames = filename_array;
current_dir->num_filenames = i;
current_dir->attrib = fileattrib_array;
return current_dir;
}
|
the memory allocated for
current_dir, filename_array & fileattrib_array
is not freed: is it ok or is it a misconception of the code?
Thanks _________________ softwares for artists on video game systems - http://www.pikilipita.com |
|
| Back to top |
|
 |
Lukasz

Joined: 19 Jan 2004 Posts: 248 Location: Denmark
|
Posted: Sat Sep 20, 2008 6:56 pm Post subject: |
|
|
There is nothing wrong with the function itself, but you are correct that you need to free all allocated memory. This needs to be done a in seperate function like freeFilenames(filename_t* fn) once you no longer need the structure.
Unlike in C++ and other object oriented languages where you have a deconstructor called once you free or no longer use a object on the stack, you in C need to call this function explicitly. In C++ the pitfall is to forget to free all the allocated memory, but in C you get the addional pitfall of forgetting to call the deconstructor in the first place ;-) _________________ Lukasz.dk |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|