Tomás Batista
Tomás Batista

Reputation: 19

How to pass a double pointer to a function without segmentation fault C language

I'm trying to pass a double pointer as an argument to a function and I can't see why the segmentation fault happen...

Here is the function:

void create_path_list(char *path_, char ***path) {
// Convert the path (string) into a list of directories
   char *token = NULL;
   int i = 0;

   *path = (char **) realloc(*path, (i + 1) * sizeof(char *));
   (*path)[i] = (char *) malloc(2);
   strcpy((*path)[0], "/");
   for(token = strtok(path_,"/"), i = 1; token != NULL; token = strtok(NULL, "/"), ++i)
   { 
     *path = (char **) realloc(*path, (i + 1) * sizeof(char *));
     (*path)[i] = (char *) malloc(sizeof(token) + 1);
     strcpy((*path)[i], token);
   }
}

Here is the main:

int main(){
   char **path = NULL;
   create_path_list("/dir1/dir2/dir3/file.txt", &path);
   return 0;
}

Upvotes: 0

Views: 601

Answers (1)

2501
2501

Reputation: 25752

sizeof(token)

Will give the size of token, which is a pointer. That will not allocate enough space to copy for the entire string

malloc(sizeof(token) + 1);
strcpy((*path)[i], token);

You should replace sizeof with a strlen


You are passing a string literal to you function and then try to change it with strtok(). You will have to pass a mutable string.

char str[] = "/dir1/dir2/dir3/file.txt" ;
create_path_list( str , &path);


Also I don't see how can you know how large is your allocated array if pointers. You will have to either return the size or NULL terminate the array.

Set the last element to null:

 *path = (char **) realloc(*path, (i + 1) * sizeof(char *));
 (*path)[i] = NULL ;

And print it outside the function

for( size_t i = 0 ; path[i] ; i++ )
{
    printf("%s" , path[i] ) ;
}

Upvotes: 3

Related Questions