#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);
}

有人能帮助理解为什么我在上面的代码中得到警告吗?

最佳答案

首先,你向用户请求一些输入,然后(简单地说)使用程序存在的目录。我想你还想做点别的
int i = scandir( userd, &namelist , 0 , alphasort);
我想知道如果有人输入的数据大于20(即userd的大小)时会发生什么情况
如果;)你做的是好的,因为你有双指针并且free(namelist); and free(namelist[j]);是在malloc()里面完成的,但是在scandir()之后不终止程序有点糟糕,因为它会跳到i<0而产生free(namelist);(在我的计算机中:undefined behaviour)。您也可以只在*** glibc detected *** free(): invalid pointer:部分添加free()
这就是我想你要找的代码:

#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;
}

关于c - 编译错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4533435/

10-16 04:53