Search code examples
csegmentation-faultrealloc

C: SEGFAULT with realloc on char **


Another one in my series of problems with this code. I have below function which is comparing arg with every string in the array of strings reference :

char compare(char *arg)
{
        int iter=0;
        char retchar='0';

        while(iter < no_of_ref)
        {
        //      printf("arg : %s , reference : %s \n",arg,reference[iter]);
                if((strstr(reference[iter],arg) != NULL) || (strstr(arg,reference[iter]) != NULL))
                {
                        retchar='1';
                        break;
                }
          iter++;
        }
return retchar;
}

reference is global char ** , but built up dynamically inside main as below:

reference = calloc(CHUNK, sizeof(char *));

Then some code, then:

                        temp_in[pre_pip+1]='\0';
                        reference[no_of_ref]=malloc(strlen(temp_in) + 1);
                        strcpy(reference[no_of_ref++],temp_in);
                        memset(&temp_in,'\0',sizeof(temp_in));
                        pre_pip = -1;
   printf("INDEX: %d, address : %p , val : %s\n",no_of_ref-1,reference[no_of_ref-1],reference[no_of_ref-1]);      //DEBUG
                }
                /*If allocated buffer is at brim, extend it for CHUNK char *  further*/
                if(no_of_ref == (tr*CHUNK - 2))
                {
                        current_size = tr*CHUNK*sizeof(char *);

                        char *retalloc = realloc(reference,current_size + CHUNK*sizeof(char *));
                                if(retalloc == NULL)
                                        perror("ERROR on realloc");
                                else
                                {
                                        printf("Realloced successfully: %p\n",retalloc);
                                        tr++;
                                }

The code running fine for test case where no need to realloc arises, i.e. Number of input strings is less than CHUNK. In case of realloc, I'm getting SEGFAULT from function. Below is for one of the run:

Program terminated with signal 11, Segmentation fault.
#0  __strstr_sse42 (s1=0x3839393433333230 <Address 0x3839393433333230 out of bounds>, s2=0x6020c0 <cmp> "8956549122") 

Solution

  • When realloc actually reallocates the memory you pass to it, then that pointer you pass as an argument still points to the old memory area. The realloc function returns a pointer to the new memory, so you have to assign that to e.g. reference.