2014-01-21 22 views
-3

当我运行我的应用程序,如./a.out我有这个错误: 我编译我的应用程序,如:gcc test1.c。 内存故障我的简单程序中的内存错误C

我的代码是

int main (void) 
{ 
    DIR *dp; 
    struct dirent *ep; 
    const char *path_dir ="/home/risorse/ae23054/Giuseppe";//Inserire la directory qui 

    dp = opendir (path_dir); 
    if (dp != NULL) 
    { 
     while (ep = readdir (dp)){ 
     printf(ep->d_name); 
     char nome_file[256]; 
     strcpy(nome_file,ep->d_name); 

     FILE *fd=fopen(nome_file, "a+"); 
     fprintf(fd,"\nEXIT"); 
     fclose(fd); 
     } 
     (void) closedir (dp); 
    } 
    else 
    perror ("Non posso aprire la directory"); 

    return -1; 
} 

感谢

+4

你做任何调试 –

+1

检查'fopen'的返回值。 – sujin

+0

你没有初始化'ep'结构? –

回答

3

您使用的fopen导致没有检查它是NULL。

2

如果当前目录不是path_dir和当前的工作目录不包含具有相同名称的文件,在文件path_dirfopen将返回NULL。

你的程序是最有可能崩溃,因为你不尝试使用它(在下面fprintffclose调用之前检查返回值。

一个可能的解决办法是设法前更改到目录fopen的文件。这将意味着你得到预期的行为。虽然,你还需要检查的情况下,空的文件被删除/移动你的目录条目的后面。

... 
dp = opendir (path_dir); 
if (dp != NULL) 
    { 
    fchdir(dirfd(dp)); 
...