读取大小4无效

时间:2012-03-08 04:18:56

标签: c valgrind

您好,我有以下代码:

struct Edge
{
    Node * nodeA, * nodeB;
    int weight;
};
.
.

这只是简单地改为边缘其他地方。

.
.

int cmp(const void *b, const void *a)
{
    Edge * e1 = (Edge*)a;
    Edge * e2 = (Edge*)b;
    printf(" %d++", getWeight(e1));
    printf(" %d++", getWeight(e2));
    if (getWeight(e1) != getWeight(e2))
        return (getWeight(e1) < getWeight(e2)) ? -1 : 1;
    return 0;
}

void sortEdges(Edge ** edgeList, int numEdges)
{
    qsort(edgeList, numEdges, sizeof(Edge*), cmp);
}

Valgrind告诉我,我有一个大小为4的无效读数,当我输出边缘权重的值时,我得到了意想不到的结果。我只能得出结论,我对Edge *的演员有问题,或者sizeof以某种方式不按照我的想法行事。如果您需要任何信息,请告诉我。

1 个答案:

答案 0 :(得分:3)

有两种方法可以纠正您的代码 1.如果edgeList是(Edge *)的数组。

int cmp(const void *b, const void *a)
{
    Edge ** e1 = (Edge**)a;//notice
    Edge ** e2 = (Edge**)b;//notice
    printf(" %d++", getWeight(*e1));//notice
    printf(" %d++", getWeight(*e2));//notice
    if (getWeight(*e1) != getWeight(*e2))//notice
        return (getWeight(*e1) < getWeight(*e2)) ? -1 : 1;//notice
    return 0;
}

void sortEdges(Edge ** edgeList, int numEdges)
{
    qsort(edgeList, numEdges, sizeof(Edge*), cmp);
}

2,如果edgeList是Edge的数组。

int cmp(const void *b, const void *a)
{
    Edge * e1 = (Edge*)a;
    Edge * e2 = (Edge*)b;
    printf(" %d++", getWeight(e1));
    printf(" %d++", getWeight(e2));
    if (getWeight(e1) != getWeight(e2))
        return (getWeight(e1) < getWeight(e2)) ? -1 : 1;
    return 0;
}

void sortEdges(Edge * edgeList, int numEdges)//notice
{
    qsort(edgeList, numEdges, sizeof(struct Edge), cmp);//notice
}