I am creating directory structure objects for a tree. The problem I am working on is the create directory tree function. The first, second, and third loop work but when it goes through the while loop for the second time and the nested for loop a second time, a segmentation fault occurs. Am I using the **variable incorrectly?
My friend once told me that pointers were similar to arrays and I also thought that **variables could be used similar to the argv parameter.
If this is idea isn't right or I am just working with the variable incorrectly, please let me know! Thanks.
Code:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#define MAXD 10 /* 3 <= depth < MAXD */
#define MAXB 10 /* 3 <= breadth < MAXB */
void create_dir_tree();
void traverse_dir_tree();
int find_total_no_dirs();
int find_dir();
struct dir {
char *path; /* path to get to this dir, not including this */
char *name; /* current dir name */
int d; /* 3 <= depth level < MAXD */
/* the init_d is depth 0, its immediate subdirs are depth 1, etc. */
int b; /* 3 <= breadth or number of sub dirs < MAXB */
struct dir *up; /* points to the parent */
struct dir **down; /* points to the sub dirs of this dir. Note the TWO *'s */
struct dir *left; /* left sibling dir, use circular link */
struct dir *right; /* right sibling dir, use circular link */
};
int main(int argc, char **argv) {
struct dir *hp;
int b,d,n,flag;
char *init_d,tst_dir[100];
if (argc < 4) {
printf("usage: hw3 root_d d b\n");
return 1;
}
argv++; /* skip the command itself */
init_d = *(argv++);
d = atoi(*argv++);
b = atoi(*argv++);
create_dir_tree(&hp,init_d,d,b);
traverse_dir_tree(hp);
n = find_total_no_dirs(hp);
strcpy(tst_dir,"root_d/a/bb/ccc/dddd");
if ((flag = find_dir(hp,tst_dir)))
printf("dir %s found\n",tst_dir);
else
printf("no dir %s found\n",tst_dir);
return 0;
}
/* create directories breadth first */
void create_dir_tree(struct dir **hp,char *name,int d, int b) {
printf("create_dir_tree init_d=%s depth=%d breadth=%d\n",name,d,b);
(*hp)=malloc(sizeof(struct dir));
(*hp)->path = NULL;
(*hp)->name = name;
(*hp)->d = 0;
(*hp)->b = 1;
(*hp)->up = NULL;
(*hp)->left=NULL;
(*hp)->right=NULL;
struct dir **open;
struct dir *cp;
struct dir **tp;
open=hp;
int i;
for(i=0;i<d;i++){
while(open){
tp=open;
int j;
cp=*open;
for(j=0;j<b;j++){
printf("depth=%d breadth=%d\n",i,j);
struct dir *tmp=malloc(sizeof(struct dir));
tp++;
tp=&tmp;
tmp->d=i;
tmp->b=j;
if(j==0){
cp->down=&tmp;
}
else{
(*(cp->down))->right=tmp;
cp->down=&tmp;
free(tmp);
}
}
printf("made it out depth=%d breadth=%d\n",i,j);
open++;
}
}
}