ls -l 구현 중 질문

rlaguddls10의 이미지

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);
}
karkayan의 이미지

gdb를 쓰는게 제일 빨리 알 수 있겠네요.
구글에서 "gdb 세그멘테이션 오류" 등으로 검색하면 gdb로 어떻게 원인을 알아 낼 수 있는지 자세한 설명이 많이 나올겁니다.

raymundo의 이미지

곳곳에 printf라도 집어넣어 확인해봤다면 정확히 어느 라인에서 폴트가 나는지도 알 수 있으셨을 거고...
컴파일 할 때 나오는 경고만 잘 보셔도 많은 게 해결될 것 같습니다.

// 두번째 인자로 문자열이 와야 하는데 char 가 오고 있음
strcpy(lt[num].mode, type(st.st_mode));
 
// ctime의 인자는 주소여야 하고
// 반환값도 ti 의 타입과 맞지 않음
ti=ctime(st.st_mtime)
 
 
	for(i=0;i<num;i++)
	{
// 이건 경고가 뜨진 않았겠지만, num이 아니라 i여야
		printf("%s\n", array[num]);
	}

좋은 하루 되세요!

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.