qsort segfault in C

ぐ巨炮叔叔 提交于 2019-12-07 18:13:30

One of your problems is:

qsort(table, entry_num, sizeof(struct dirent), &compare_dirent);

should be:

qsort(table, entry_num, sizeof(struct dirent *), &compare_dirent);

The third element is width, the size of each object. Since table is an array of struct dirent *, that is what you want the size of.

You're also misusing the value returned by readdir. From the docs:

The pointer returned by readdir() points to data which may be overwritten by another call to readdir() on the same directory stream.

That means it's quite possibly all of the values in your table are the same pointer, with the same value. You can use readdir_r, or just allocate struct dirent (one for each readdir call), and memcpy the value in place.

An alternative is to change it to be an array of struct dirent, in which case you would use your original qsort call.

Your code doesn't save the dirents! You allocate memory to hold pointers to them, but then you never allocate any memory to hold the actual entries. So when you go to sort, your pointers point to objects that no longer exist.

This line of code is broken:

table[entry_num] = entries;

This saves the pointer that points to the dirent now. But that pointer is meaningless later when it no longer points to the dirent. You can't save the pointer to use later, you have to save the actual entry.

The data returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream.

So you need something like:

table[entry_name] = malloc(sizeof(struct dirent));
memcpy(table[entry_name], entries, sizeof(struct dirent));

Don't forget to free them when you're done.

Matthew Flaschen's answer is also correct. You passed the wrong size to qsort.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!