Page 1 of 1

memory leak on read directory example?

Posted: Sat Sep 20, 2008 9:08 am
by kouky
I'm chasing a memory leak in my homebrew project...

I'm using this read directory code from the ogg player example...

Code: Select all

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 &#40;&#40;ret = fioDopen&#40;directory&#41;&#41; < 0&#41; &#123;
		//printf&#40;"Error opening dir\n"&#41;;
		return NULL;
	&#125;

	i=0;
	n_dir=0;
	n_reg=0;

	while &#40;fioDread&#40;ret, &record&#41; > 0&#41; &#123;
		/*Expand array if too small */
		if &#40;i % FILEARRAYBUFFER == 0&#41; &#123;
			filename_array   = realloc&#40;filename_array,
					sizeof&#40;char*&#41; * &#40;i+FILEARRAYBUFFER&#41;&#41;;
			fileattrib_array = realloc&#40;fileattrib_array,
					sizeof&#40;int&#41;   * &#40;i+FILEARRAYBUFFER&#41;&#41;;
		&#125;

		/*Copy filename into array */
		filename_array&#91;i&#93; = malloc&#40;strlen&#40;record.name&#41;+1&#41;;
		strcpy&#40;filename_array&#91;i&#93;, record.name&#41;;
		fileattrib_array&#91;i&#93; = record.stat.mode;

		/*Keep track of number of files */
		if &#40;FIO_SO_ISDIR&#40;record.stat.mode&#41;&#41; &#123;
			n_dir++;
		&#125;

		if &#40;FIO_SO_ISREG&#40;record.stat.mode&#41;&#41; &#123;
			n_reg++;
		&#125;
		i++;

	&#125;

	if &#40;ret >= 0&#41; fioDclose&#40;ret&#41;;

	current_dir->filenames = filename_array;
	current_dir->num_filenames = i;
	current_dir->attrib = fileattrib_array;
	return current_dir;

&#125;
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

Posted: Sat Sep 20, 2008 6:56 pm
by Lukasz
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 ;-)