简体   繁体   中英

compare function giving segmentation fault in qsort

I did a compare function for qsort and it causes a segmentation fault. why is this happening and how to fix it?

example my two arrays are:
G->grades = [2,3,3,2,2,2] 
G->order =  [0,2,3,4,5,6]

I want to sort G->order using G->grades values. So the output should be:
G->order = [2,3,0,4,5,6]

u32* vert_grades;

char OrdenWelshPowell(Grafostv* G)
{
    vert_grades = G->grades;
    qsort(G->order, G->n, sizeof(u32), comp_grades);
    return 0;
}

int comp_grades(const void *v1, const void *v2) {
    u32 degree1 = vert_grades[*(const u32 *)v1 - 1];
    u32 degree2 = vert_grades[*(const u32 *)v2 - 1];
    printf("degree2: %u\n", vert_grades[*(const u32 *)v2 - 1]);
    if (degree1 > degree2)
    {
        return -1;
    }
    else if (degree1 < degree2)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

pd: I dont care to order G->grades for the moment.

You have the array

G->order = [0,2,3,4,5,6]

Notice that your arrays have 6 elements, so the range of their indexing must be either 0..5 or 1..6 . Your cmp function presumes the latter, because it subtracts 1 from the index.

But the ordering array has the range 0..6 which does not suit either system. In this case the first value 0 will break the array bounds because you subtract 1 .

I suggest the initial data before sorting should be

G->order = [1,2,3,4,5,6]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM