Qsort crashing program - C

Trying to follow this example. (Sorting string string ...)
Is there something obvious that could cause this crash in stdlib qsort.c?
I also tried cstring_cmp with strncmp specifying 30 characters max, much more than mine.
* fileArray [20] seems to be correctly filled with strings.
Thank you.

char* ptr_fileName;  
char* fileArray[20];//number of files  
size_t strings_len;  

ptr_fileName = (char*)malloc((strlen(FindFileData.cFileName)+1)*sizeof(char));
memcpy(ptr_fileName, FindFileData.cFileName, strlen(FindFileData.cFileName)+1);
fileArray[i] = ptr_fileName;



strings_len = sizeof(fileArray) / sizeof(char *);          
qsort(fileArray, strings_len, sizeof(char *), cstring_cmp);   
//crashing in qsort.c

      

Comparison function c-string qsort:

/* qsort C-string comparison function */
    int cstring_cmp(const void *a, const void *b)
    {
        const char **ia = (const char **)a;
        const char **ib = (const char **)b;
        return strcmp(*ia, *ib);
        /* strcmp functions works exactly as expected from
        comparison function */
    }

      

+2


source to share


5 answers


You say that you only fill the Array file with 10 lines, leaving the 10 entries uninitialized.

When you call qsort, you are passing 20 as an argument to strings_len. This will of course lead to undefined behavior.

You must provide accurate information to qsort.



If you are passing 10 strings in an array, you must also pass 10 as the number of items to sort.

Note: If you were following my earlier answer by setting a breakpoint on cstring_cmp, you would quickly see when a comparison method is called with invalid data, leading to a crash directly.

+4


source


How do you fill in:

char* fileArray[20];

      



as it is an array of uninitialized pointers.

+2


source


Set a breakpoint on cstring_cmp and watch how it gets called each time.

See if the final crash happens inside cstring_cmp or in qsort. Check the state of the Array file just before the crash.

+2


source


* fileArray [20] seems to be filled with lines correctly.

The asterisk in front of the file array makes me suspicious about how you filled the array. I don't see anything else that might break your code.

+1


source


Since you are not initializing the contents of fileArray, it contains random memory, not legal char pointers.

0


source







All Articles