c - qsort() performance issue -
i'm sorting array of structs, each struct contains char string. problem however, struct array of approx. 900,000 elements, qsort taking alot longer expect (qsort takes 2 mins sort array); leading me think there overlooking here. sorting trivial part of assignment working on, , alone on passes time limit have program.
below relevant parts of code:
struct wordsarray //just struct thath holds *char { char word[25]; };
compare function passed qsort:
int cmpfunc(const void *a, const void *b) { const struct wordsarray *a1; a1 = (wordsarray*)malloc(sizeof(wordsarray)); const struct wordsarray *b1; b1 = (wordsarray*)malloc(sizeof(wordsarray)); a1 = (struct wordsarray*)a; b1 = (struct wordsarray*)b; return strcmp(a1->word, b1->word); }
my call qsort:
wordsarray *allwordsarray; allwordslist = (wordsarray*)malloc(sizeof(wordsarray)*listsize); qsort(allwordslist->word, listsize, sizeof(struct wordsarray), cmpfunc);
thanks input.
the problem cmpfunc
's implementation: leaks memory faster fire hydrant!
you allocating (wordsarray*)
pointers write on them on next line, creating memory leak in process. need removing malloc
s:
int cmpfunc(const void *a, const void *b) { const struct wordsarray *a1 = (struct wordsarray*)a; const struct wordsarray *b1 = (struct wordsarray*)b; return strcmp(a1->word, b1->word); }
Comments
Post a Comment