I have this code:
char* findFile(char* path, char* fileName)
struct dirent *dirEntry;
while (NULL != (dirEntry = readdir(thisDir)) && notFound)
if (dirEntry->d_type == DT_DIR)
if (dirEntry->d_name != '.')
char *nextPath = malloc(512);
nextPath[nextPathLen] = '/';
else if (dirEntry->d_type == DT_REG)
if (strcmp(fileName, dirEntry->d_name) == 0 )
char* foundPath = malloc (512);
Replace the line
char * f = findFile(nextPath, fileName); if (f != NULL) return f;
You need to check the return value is not NULL - if it is NULL you want to keep looking.
You must also return NULL at the end of the function to indicate that nothing was found in that iteration. It is "undefined behaviour" to not have all code paths returning a value - that means anything could happen. Eg, you could get spurious addresses being returned instead of what you want in the case you don't find anything (which is to return NULL).
There are a few other issues - you'll have memory leaks with all those mallocs and no frees, but get it working first and then tackle that.