Thursday 15 May 2014

arrayofstring - Losing values with iterative realloc in C -



arrayofstring - Losing values with iterative realloc in C -

i working in c netbeans8.0 have read files in iterative approach list of words. is, in single iteration file read array of strings , merge array single array.

void merge_array(char** a,int* m, char** b,int n) { //............. add together memory ..............*/ void *tmp = realloc(a, (*m+n) * sizeof(*a)); if (tmp == null) { perror("merging -> not reallocate"); exit(exit_failure); } = tmp; memset(a+(*m), 0, n*sizeof(*a)); //............. re-create strings in b ..............*/ 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 replicate string"); exit(exit_failure); } memcpy(a[i], b[j], wlen+1); j++; } (*m) = (*m)+n; // resetting count printf("confirm - %s, %d\n",a[0],*m); }

above function reads contents of file. in main above function called iteratively , merged single array named 'termlist'. main code 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 first file initializing 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 problem that, after 1st 2 iterations, within function works fine in main values of termlist[0], termlist[1] turns out junk.. first 2 words read first file lost. 3rd iteration returns failure @ merge_array function call.

output

******* 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 not able identify problem this.. please help this..

realloc arrayofstring

No comments:

Post a Comment