Array problem in C
I am very confused. In the while loop I am adding each file name into an array and printing it afterwards.
However in the for loop it prints some weird things and stops executing in the middle.
Please help me to fix it.
char *commands[1000];
char *str;
DIR * dir;
struct dirent * entry;
char *env = getenv("PATH");
do {
str = strsep(&env, ":");
if(str != NULL)
if(strlen(newEnv) > 0) {
dir = opendir(str);
if( dir == NULL ) break;
flag = 0;
while((entry = readdir(dir)) != NULL) {
commands[++count] = entry->d_name;
printf("---%i %s\n", count ,commands[count]); // prints fine
}
closedi开发者_运维知识库r(dir); // close directory
}
} while(newEnv);
commands[++count] = '\0';
printf("count = : %i\n", count);
for(int i = 0; i < count; i ++)
{
if(commands[i] == NULL)
break;
printf("aaa%i %s\n\n", i, commands[i]); //problem loop
}
You are setting your pointers pointing into the dir
struct received by readdir
. However, that struct is deallocated by closedir
.
You need to copy the strings (strdup
and friends).
commands[++count] = entry->d_name
doesn't copy the entry->d_name
string into commands[++count]
, but merely assigns the pointer. In the next iteration entry->d_name
is overwritten since readdir
uses static memory for returning the result.
Use strcpy
instead and allocate the memory yourself.
The problems:
- you add pointers to the array, which point to strings that will be deallocated by
readdir/closedir
shortly after - if the starting value of
count
is 0,commands[0]
is never assigned to and contains garbage - the
commands[++count] = '\0';
line seems to be a mistake, but luckily it adds 1 tocount
so theprint count
line prints right number and thefor
loop iterates over the right range
In addition to @Eugene Homyakov's answer:
You should not rely in your last loop on "commands" array to be initialized with NULL values.
精彩评论