t is a temporary pointer, which you check before assigning to cat
This is because realloc can return NULL, so assigning directly to the pointer risks a memory leak.
Two versions -
Code:
char** get_categories(void)
{
DIR* dp = NULL;
struct dirent* ds;
char** cat = NULL;
int i=1;
dp = opendir("rubrieken/");
while( (ds = readdir(dp)) != NULL )
{
if ( (strcmp(ds->d_name, ".") != 0) && (strcmp(ds->d_name, "..") != 0))
{
void *t = realloc( cat, (i++)*sizeof(char*) );
if ( t != NULL ) {
cat = t;
cat[i-1] = malloc( sizeof(char)*(strlen(ds->d_name)+1) );
if ( cat[i-1] != NULL ) {
strcpy(cat[i-1], ds->d_name);
}
}
}
}
closedir( dp );
return cat;
}
char** get_categories(void)
{
DIR* dp = NULL;
struct dirent* ds;
char** cat = NULL;
int i=0;
dp = opendir("rubrieken/");
while( (ds = readdir(dp)) != NULL )
{
if ( (strcmp(ds->d_name, ".") != 0) && (strcmp(ds->d_name, "..") != 0))
{
void *t = realloc( cat, (i+1) * sizeof(cat[0]) );
if ( t != NULL ) {
cat = t;
cat[i] = malloc( sizeof(cat[i][0])*(strlen(ds->d_name)+1) );
if ( cat[i] != NULL ) {
strcpy( cat[i], ds->d_name);
i++;
}
}
}
}
closedir( dp );
return cat;
}
The second one avoids sizeof on types, but instead goes for sizeof on objects.