Commit 72149942 authored by Rémi Denis-Courmont's avatar Rémi Denis-Courmont

vlc_loaddir: avoid realloc at every iteration

parent 04ad4fc7
...@@ -353,54 +353,59 @@ int vlc_loaddir( DIR *dir, char ***namelist, ...@@ -353,54 +353,59 @@ int vlc_loaddir( DIR *dir, char ***namelist,
int (*select)( const char * ), int (*select)( const char * ),
int (*compar)( const char **, const char ** ) ) int (*compar)( const char **, const char ** ) )
{ {
if( select == NULL ) assert (dir);
if (select == NULL)
select = dummy_select; select = dummy_select;
if( dir == NULL )
return -1;
else
{
char **tab = NULL; char **tab = NULL;
char *entry;
unsigned num = 0; unsigned num = 0;
rewinddir( dir ); rewinddir (dir);
while( ( entry = vlc_readdir( dir ) ) != NULL ) for (unsigned size = 0;;)
{ {
char **newtab; errno = 0;
char *entry = vlc_readdir (dir);
if (entry == NULL)
{
if (errno)
goto error;
break;
}
if( !select( entry ) ) if (!select (entry))
{ {
free( entry ); free (entry);
continue; continue;
} }
newtab = realloc( tab, sizeof( char * ) * (num + 1) ); if (num >= size)
if( newtab == NULL )
{ {
free( entry ); size = size ? (2 * size) : 16;
char **newtab = realloc (tab, sizeof (*tab) * (size));
if (unlikely(newtab == NULL))
{
free (entry);
goto error; goto error;
} }
tab = newtab; tab = newtab;
tab[num++] = entry;
} }
if( compar != NULL ) tab[num++] = entry;
qsort( tab, num, sizeof( tab[0] ), }
(int (*)( const void *, const void *))compar );
if (compar != NULL)
qsort (tab, num, sizeof (*tab),
(int (*)( const void *, const void *))compar);
*namelist = tab; *namelist = tab;
return num; return num;
error:{ error:
unsigned i; for (unsigned i = 0; i < num; i++)
free (tab[i]);
for( i = 0; i < num; i++ ) free (tab);
free( tab[i] );
free( tab );
}
}
return -1; return -1;
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment