0

我这里有一个非常奇怪的问题,并没有设法在网上找到答案。

在尝试读取 errno 时出现段错误的 printf 语句调试后出现。在 readdir() 调用到达目录流的末尾并返回 NULL 之后,将有问题的行逐一注释掉,因为它们会导致 segfault 导致必须注释掉对 errno 的每个引用。

即便如此,代码稍后在尝试访问另一个自动变量 file_count 时也会出现段错误。

到底是怎么回事?这是堆栈溢出吗?我如何让它停止?

代码如下,如果你觉得有必要通过它。所有对 errno 有问题的引用都被删除,程序在成功执行倒数第三行后出现段错误:printf("printing file_count\n");.

EDIT1:这是一个 GDB 回溯:

#0  0xc95bf881 in strcpy () from /usr/lib/libc.so.1
#1  0x08051543 in dir_get_list (user=0x8047b88 "user1") at maildir.c:231
#2  0x08050f3e in main (argc=4, argv=0x80479f4) at maildir.c:43

结束编辑1

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>

#define MAX_FILENAME_LENGTH 255
#define MAX_USERNAME_LENGTH 40
#define MAX_PASSWORD_LENGTH 20


typedef int bool;

#define true 1
#define false 0


struct files_struct{
    /*The number of email messages in a maildir.*/
    int count; 

    /*A pointer to an array of pointers to the strings of the filenames. */
    char **FileNames;

    /*A pointer to an array of ints that give the corresponding size of the file.*/
    int  *FileSize;
};

typedef struct files_struct FilesStruct;


void dir_set_path(char* path);
bool check_user(char* username, char* pass);
FilesStruct* dir_get_list(char* user);
void delete_mail(char* user, char* filename);
char* get_file(char* user, char* filename);



FilesStruct* dir_get_list(char* user){
    char maildir_name[MAX_FILENAME_LENGTH];
    DIR * maildir_fd;
    struct dirent *maildir_p;

    strcpy(maildir_name,"./");
    strncat(maildir_name,user,MAX_USERNAME_LENGTH);
    strcat(maildir_name,"/");

    if((pthread_mutex_lock(&maildir_root_mutex))<0)
    perror("ERROR on locking maildir_root_mutex");
    printf("Opening directory ""%s""\n",maildir_name);
    if((maildir_fd = opendir(maildir_name))==NULL)
    perror("ERROR on opendir");

    int file_count = 0;

    /* scan over entire directory, counting number of files to that data can be properly malloced */
while(1){
    if((maildir_p = readdir(maildir_fd))==NULL){
        closedir(maildir_fd);
        printf("breaking loop\n");
        break;
    }
    char file[MAX_FILENAME_LENGTH+1];
    strcpy(file,maildir_p->d_name);

    printf("File %d: '%s'\n",file_count+1,maildir_p->d_name);
    /* if the file is a file other than an email */
    if(!strcmp(".",file)||!strcmp("..",file)||!strcmp("pass",file)||!strcmp(".svn",file)){
        printf("Continuing without incrementing file_count\n");
        continue;
    }
    file_count++;
}
printf("%u\n",maildir_fd);
printf("printing file_count\n");
printf("%d",file_count);
printf("file_count printed successfully");

/* 省略附加代码 */

4

1 回答 1

0

我最近遇到了这个。在我的例子中,另一个模块声明了:

int errno = 0;

作为一个全局变量,而不是#include errno.h。任何使用“正确”errno 的代码都会立即出现段错误。

于 2016-11-04T09:01:05.580 回答