1

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 .

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
bird12358
  • 39
  • 6

3 Answers3

2

In this code snippet

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

there is passed the pointer tagid to the function read by value. That is the function deals with a copy of the value of the original pointer. Changing the copy does not influence on the original pointer.

You need to pass the pointer by reference through pointer to it. That is the function should be declaration like

int read(char *** tag_ids, int * nbtag)

and called like

int error = read(&tagid,&nbtag);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
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

Davide B
  • 36
  • 2
1

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);
carce-bo
  • 480
  • 2
  • 10