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

半城伤御伤魂 提交于 2019-12-12 04:54:04

问题


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;
}

回答1:


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] ) ;
}


来源:https://stackoverflow.com/questions/26534129/how-to-pass-a-double-pointer-to-a-function-without-segmentation-fault-c-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!