opendir segmentation fault

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
#include<dirent.h>
#include<unistd.h>
int makargv(const char*, const char*, char ***);
int main(int argc, char *argv[]){
	if(argc != 2){
		printf("Usage: %s search\n", argv[0]);
		return -1;
	}
	char **pathToken;
	char *pathVariable = NULL;
	int i = 0;
		if((pathVariable = getenv("PATH")) == NULL){
			perror("Path Not Found");
			return -1;
		}
	int tokenCount = makargv(pathVariable, ":", &pathToken);
	DIR* dirPtr[tokenCount];
	struct dirent *direntPtr[tokenCount];
	for(i = 0; i < tokenCount; i++){
	printf("%s\n", pathToken[i]);
	dirPtr[i] = opendir(pathToken[i]);
		while( (direntPtr[i] = readdir(dirPtr[i])) != NULL)
			if(!strcmp(direntPtr[i]-> d_name, argv[1]))
				 printf("%s/%s\n", pathToken[i], argv[1]); 
	}
	return 0;
}

it gives seqmentation fault after 1st iteration of for loop. whats wrong with this ?
What's the value of tokenCount?
its 12
What is makargv? Do you have the source for it? If you do, why haven't you posted it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int makargv(const char* str, const char* delimiter, char ***argvp){
	int tokens = 0;
	int i, error;
	const char *snew;
	char *t;
	if(str == NULL || delimiter == NULL || argvp == NULL){
		errno = EINVAL;
		return -1;
	}
	*argvp = NULL;
	snew = str + strspn(str, delimiter);
		if( (t = malloc(strlen(snew) + 1)) == NULL) return -1;
	strcpy(t, snew);
	if(strtok(t, delimiter) != NULL)
		for(tokens = 1; strtok(NULL, delimiter); tokens++);
		if((*argvp = malloc(tokens * sizeof (char *))) == NULL){
			error = errno;
			free(t);
			errno = error;
			return -1;
		}
		
		if(!tokens) free(t);
		else{
		
			strcpy(t, snew);
			**argvp = strtok(t, delimiter);
			for(i = 1; i < tokens; i++) *(*(argvp) + i) =  strtok(NULL, delimiter);
		}
		*(*(argvp) + tokens) = NULL;
			return tokens;
}

k. here is the code for makargv, it just tokenize the string at given delimiter
1
2
3
if((*argvp = malloc(tokens * sizeof (char *))) == NULL){
//...
*(*(argvp) + tokens) = NULL; //out of bounds 
nop, it worked now .. there was an error in opendir .. thanks
Topic archived. No new replies allowed.