ls -l 구현 중 질문
글쓴이: rlaguddls10 / 작성시간: 수, 2019/04/10 - 11:51오후
ls -l 함수를 구현하는 도중에 중간 확인차 for문을 이용하여 파일들의 이름을 출력해보았는데
segmentation fault(core dumped)라고 뜨더군요
이 오류는 메모리 영역을 침범할때 뜨는 오류라던데 혹시 왜 그런지 알려주실수 있나요??
#define SIZE 256 #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <pwd.h> #include <grp.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char type(mode_t); char *perm(mode_t); struct list { char name[SIZE]; char mode[SIZE]; char permission[SIZE]; int nlink; char uid[SIZE]; char gid[SIZE]; int size; char time[SIZE]; }; int main(int argc, char **argv) { DIR *dp; char *dir; struct list *lt; struct stat st; struct passwd *pa; struct group *gr; struct time *ti; struct dirent *d; char array[256][256]; char path[BUFSIZ+1]; int i=0; int num=0; int mal=0; //variable to dynamic allocation; if(argc == 1) dir="."; else dir=argv[1]; if((dp=opendir(dir))==NULL) perror(dir); while((d=readdir(dp))!=NULL) { lt=(struct list *)malloc(sizeof(struct list)*mal); mal++; } rewinddir(dp); while((d=readdir(dp))!=NULL) { sprintf(path, "%s/%s", dir, d->d_name); if(lstat(path, &st)<0) perror(path); else { strcpy(lt[num].mode, type(st.st_mode)); strcpy(lt[num].permission, perm(st.st_mode)); pa = getpwuid(st.st_uid); strcpy(lt[num].uid, pa->pw_name); gr = getgrgid(st.st_gid); strcpy(lt[num].gid, gr->gr_name); lt[num].nlink=st.st_nlink; lt[num].size=st.st_size; ti=ctime(st.st_mtime); strcpy(array[num], d->d_name); num++; } } for(i=0;i<num;i++) { printf("%s\n", array[num]); } closedir(dp); exit(0); } char type(mode_t mode) { if(S_ISREG(mode)) return('-'); else if(S_ISDIR(mode)) return('d'); else if(S_ISCHR(mode)) return('c'); else if(S_ISBLK(mode)) return('b'); else if(S_ISLNK(mode)) return('l'); else if(S_ISFIFO(mode)) return('p'); else if(S_ISSOCK(mode)) return('s'); else return('0'); } char *perm(mode_t mode) { int i; static char perms[10] = "----------"; for(int i=0; i<3; i++) { if(mode & (S_IRUSR>>i*3)) perms[i*3]='r'; else if(mode & (S_IWUSR>>i*3)) perms[i*3+1]='w'; else if(mode & (S_IXUSR>>i*3)) perms[i*3+2]='x'; } return(perms); }
Forums:
gdb를 쓰는게 제일 빨리 알 수 있겠네요.
gdb를 쓰는게 제일 빨리 알 수 있겠네요.
구글에서 "gdb 세그멘테이션 오류" 등으로 검색하면 gdb로 어떻게 원인을 알아 낼 수 있는지 자세한 설명이 많이 나올겁니다.
곳곳에 printf라도 집어넣어 확인해봤다면 정확히
곳곳에 printf라도 집어넣어 확인해봤다면 정확히 어느 라인에서 폴트가 나는지도 알 수 있으셨을 거고...
컴파일 할 때 나오는 경고만 잘 보셔도 많은 게 해결될 것 같습니다.
좋은 하루 되세요!
댓글 달기