compilation error
#include<dirent.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
int main ()
{
struct dirent **namelist;
int i,j;
char userd[20];
struct stat statBuf;
printf("Enter a directory %s\n",userd);
scanf("%s",&userd);
printf("the dir is %s\n",*userd);
i=scandir(".",&namelist,0,alphasort);
printf("enter a directory name %s",*userd);
printf("scandir returned i=%d\n",&i);
if (i<0)
perror("Scandir failed to open directory I hope you understand \n");
else
{
开发者_开发百科 for(j=0;j<i;j++)
{
printf("j=%d i=%d %s\n",j,i,namelist[j]->d_name);
// lstat
free(namelist[j]);
}
}
free(namelist);
}
Can some one help to understand why am I getting warning in above code?
You have several issues in your code besides the one Tim already found:
printf("Enter a directory %s\n",userd);
uses an uninitialized variable.
printf("the dir is %s\n",*userd);
Even unnecessary dereferences the uninitialized variable.
The code around scandir(".",&namelist,0,alphasort);
looks ok (at first sight).
First of all you ask the user for some input, and then (simply speaking) use the directory the program exists. I think you want to do something else and that is
int i = scandir( userd, &namelist , 0 , alphasort);
I wonder what happen if someone enters data bigger than 20
(which is the size of userd
) ;)
AFAIK the free(namelist); and free(namelist[j]);
you do are alright since you have double pointer and malloc()
is done inside the scandir()
But not terminating the program after i<0
is a bit bad since it would just jump to free(namelist);
which would yield undefined behaviour
(In my computer : *** glibc detected *** free(): invalid pointer:
). You can as well add the free()
only in the else
part.
This is the code I think you are looking for :
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int main()
{
char userd[20];
int i,j;
struct dirent ** namelist;
//struct stat statBuf; //Unused
printf("Enter a directory : ",userd);
scanf("%s",userd);
printf("the dir is %s\n",userd);
//Uncomment this if you want the directory from the User Input
//i = scandir( userd, &namelist , 0 , alphasort);
i = scandir( "." , &namelist , 0 , alphasort);
//printf("enter a directory name : ");
printf("scandir returned i=%d\n",i);
if (i < 0)
{
perror("Scandir failed to open directory I hope you understand \n");
return -1;
}
else
{
for( j=0 ; j<i ; j++)
{
printf("j=%d i=%d %s\n",j,i,namelist[j]->d_name);
free(namelist[j]);
}
free(namelist);
}
return 0;
}
scanf("%s",&userd);
Should be
scanf("%s", userd);
精彩评论