'Fill a char ** in function argument lead to SIGSEVG [duplicate]

I want to fill a char ** variable from a function. When I used that filled value outside the filling function, I get an error.

code 139 (interrupted by signal 11: SIGSEGV)

Here is my filling function

int read(char ** tag_ids, int * nbtag)
{
 ......
// Loop through tags
*nbtag = tagCount;
tag_ids =  (char**)malloc(tagCount * sizeof(char*));

for (idx = 0; idx < tagCount; idx++) {
    error = readtag( idx, &tagData);

      tag_ids[idx] = (char *)malloc(sizeof(char)* (tagData.epcLen+1));
      if( tag_ids[idx] == NULL) {
      printf("error \n");
      }

      strcpy(tag_ids[idx], epcStr);
      printf("strcpy length %d data %s \n", tagData.epcLen, epcStr); // data OK
      printf(" strcpy length %d data %s \n", tagData.epcLen, tag_ids[idx]); // data OK

  }

return 0;
}

When I use that function:

char ** tagid = NULL;
int nbtag;
int error = read(tagid,&nbtag);

for (int i = 0 ; i<nbtag; i++){
    printf("---> tag index : %d/%d \n", i, nbtag);
    if( tagid == NULL) {
      printf("NULL pointer \n");  // Detect pointer NULL why ???
    }
    if( tagid[i] == NULL) {
      printf("NULL pointer \n");
    }
    printf("---> tag index : %d id %s \n", i, tagid[i]); // SIGSEGV
}

I think the char ** variable in argument of my function is a copy of my original variable but I don't really understand how to fill a char ** from function .



Solution 1:[1]

I think you can find a complete answer here, aniway if you want to modify the value of a char** variable and use it outside the functione, you need to use char*** passing argument by reference

Solution 2:[2]

Indeed, youre allocating a copy of the variable.
A good way of checking this, is printing &tag_ids outside and inside of the function. You'll see the values are different. If you want to allocate a double pointer inside a function, you need to pass a reference of the variable to be allocated. i.e.:

int func(char ***tag_ids, int *nbtag) {
    *tag_ids = (char **)malloc(...);
    ...
}

and call the function like:

char **tagids = NULL;
int nbtag = 0;
int error = func(&tagids, &nbtag);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Davide B
Solution 2