读/写错误或堆栈变量会导致段错误。为什么?

时间:2013-06-01 06:10:53

标签: c segmentation-fault stack-overflow

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

在使用printf语句进行调试后,在尝试读取errno时出现了段错误。在readdir()调用到达目录流的末尾并返回NULL之后,逐条注释有问题的行会导致段错误导致必须注释掉对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

END EDIT1

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

/ *附加代码OMITTED * /

1 个答案:

答案 0 :(得分:0)

我最近遇到过这个。在我的实例中,另一个模块宣称:

session_write_close()

作为全局,而不是#including errno.h。任何使用&#34;正确&#34;的代码errno会立即发生段错误。