views:

224

answers:

5

Trying to follow this example. (Section String sorting...)
Is there anything obvious that would make this crash in stdlib's qsort.c?
I also tried *cstring_cmp* with strncmp specifying 30 chars max, much more than I have.
*fileArray[20] seems to be correctly populated with strings.
Thanks.

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

qsort c-string compare function:

/* 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  A: 

How do you populate:

char* fileArray[20];

as it stands, it's an array of uninitialised pointers.

anon
Added how I populate the array.
Tommy
No you haven't. Post the complete, real code.
anon
+1  A: 

*fileArray[20] seems to be correctly populated with strings.

The asterisk before fileArray makes me veeeery suspicious about the correctness of the way you populated the array. I don't observe anything else that might break your code.

Pavel Shved
A: 

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

soru
+2  A: 

Set a breakpoint in cstring_cmp, and watch as it is called each time.

See if the ultimate crash happens inside cstring_cmp, or in qsort. Check the state of the fileArray just before the crash.

abelenky
+4  A: 

You say you are only filling fileArray with 10 strings, leaving 10 entries uninitialized.

When you call qsort, you pass 20 as the strings_len argument. This will, of course, result in undefined behavior.

You have to give qsort accurate information.

If you are passing 10 strings in the array, you must also pass the number 10 as the number of elements to be sorted.

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

abelenky