0

I am working in C with Netbeans8.0 I have to read files in an iterative approach to get list of words. That is, in single iteration a file is read into an array of strings and then merge this array into a single array.

void merge_array(char** a,int* M, char** b,int N)
{
    //............. Add  extra memory to a ..............*/
    void *tmp = realloc(a, (*M+N) * sizeof(*a));
    if (tmp == NULL)
    {
        perror("Merging -> Could not reallocate");
        exit(EXIT_FAILURE);
    }
    a = tmp;
    memset(a+(*M), 0, N*sizeof(*a));

     //............. copy strings in b to a ..............*/
    int i,j=0;
    for(i=*M; i<((*M)+N); i++)
    {
        size_t wlen = strlen(b[j]);
        a[i] = malloc((wlen+1) * sizeof(char));
        if (a[i] == NULL)
        {
            perror("Failed to replicate string");
            exit(EXIT_FAILURE);
        }            
        memcpy(a[i], b[j], wlen+1);
        j++;
    }

    (*M) = (*M)+N;                // resetting the count

    printf("Confirm - %s, %d\n",a[0],*M);
}

Above function reads the contents of a file. In main above function is called iteratively and merged into a single array named 'termlist'. Main code is given below

char** termlist;
int termCount=0;
while(files[i]){        
    char **word_array;        
    int wdCnt,a;

    char* tmp = (char*) malloc(strlen(path)*sizeof(char));
    strcpy(tmp,path);   strcat(tmp,files[i]);   strcpy(files[i],tmp);

    printf("\n\n******* Reading file %s...\n",files[i]);  
    word_array = getTerms_fscanf(files[i],&a);      //reading contents of file  

    wdCnt = a;
    if(i==0)    // before reading the first file initializing the termlist
    {
        termlist = (char**) malloc(wdCnt*sizeof(char*));
    }            
    merge_array(termlist,&termCount,word_array,wdCnt);      
    printf("CHECK - %s, %d\n",termlist[0],termCount);

    free(word_array);
    ++i;
} 

Now the problem is that, After 1st two iterations, Inside function everything works fine but in main values of termlist[0], termlist[1] turns out to be junk.. That is first 2 words read from first file is lost. The 3rd iteration returns with failure at merge_array function call.

Output is

******* Reading F:/Netbeans C/Test Docs/doc1.txt...
Confirm - tour, 52
CHECK - tour, 52

******* Reading F:/Netbeans C/Test Docs/doc2.txt...
Confirm - tour, 71
CHECK - Ôk'aÔk'a`œ€`œ€äk'aäk'aìk'aìk'aôk'aôk'aük'aük'ah“€, 71

I am not able to identify problem with this.. Please help with this..

aswathi p
  • 13
  • 3
  • When you're having issues with memory in C, valgrind is pretty useful if you aren't on Windows for debugging this kind of stuff http://cs.ecs.baylor.edu/~donahoo/tools/valgrind/ – CalumMcCall Oct 17 '14 at 13:33
  • Data card driver of my ubuntu have some problem and i can't take net while working in Ubuntu.. So i have only windows for time being....I have bookmarked it for later try... thanks a lot – aswathi p Oct 17 '14 at 16:37

0 Answers0