简体   繁体   English

malloc中的分段错误

[英]segmentation fault in malloc

I have a written the following program and every time I try to run it I get a segmentation fault. 我编写了以下程序,每次尝试运行该程序都会遇到分段错误。 I think the problem is at the malloc of the array subsets on line 149. I tried to debug it with gdb but it says that there is a problem in function find which doesn't make any sense at all. 我认为问题出在第149行的数组子集的malloc。我尝试使用gdb对其进行调试,但它表示函数查找中存在一个问题,根本没有任何意义。 If somebody ever had a similar problem plz help. 如果有人遇到过类似的问题,请帮助。 Thanks a lot. 非常感谢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <inttypes.h>

long int N;

// a structure to represent a weighted edge in graph
struct Edge
{
    long int src, dest ;
    long int weight;
 };

 // a structure to represent a connected, undirected and weighted graph
 struct Graph
 {
 struct Edge* edge;
  };


  // A structure to represent a subset for union-find
  struct subset
  {
        long int parent;
        long int rank;
        long long int vertex;
   };


    // A utility function to find set of an element i
    long int find(struct subset subsets[], long int i)
    {
        // find the root and make root as parent of i (path compression)
       if (subsets[i].parent != i)
       subsets[i].parent = find(subsets, subsets[i].parent);

       return subsets[i].parent;
     } 


     // Union of two sets of x and y
     // (uses union by rank)
     void Union(struct subset subsets[],long int x,long int y)
     {
        long int xroot = find(subsets, x);
        long int yroot = find(subsets, y);
            // Attach smaller rank tree under root of high rank tree
        // (Union by Rank)
        if (subsets[xroot].rank < subsets[yroot].rank){
             subsets[xroot].parent = yroot;
             subsets[yroot].vertex += subsets[xroot].vertex;
        }
        else if (subsets[xroot].rank > subsets[yroot].rank){
             subsets[yroot].parent = xroot;
             subsets[xroot].vertex += subsets[yroot].vertex;
        }
        // If ranks are same, then make one as root and increment
        // its rank by one
        else
        {
        subsets[yroot].parent = xroot;
        subsets[xroot].rank++;
            subsets[xroot].vertex += subsets[yroot].vertex;
        }
       }

     // Compare two edges according to their weights.
     // Used in qsort() for sorting an array of edges
     int comp(const void* a, const void* b)
     {
        struct Edge* a1 = (struct Edge*)a;
        struct Edge* b1 = (struct Edge*)b;
        return (a1->weight - b1->weight);
      }




      int main(int argc, char *argv[])
      {
        int j;
        long int i;
        long int n1, n2, w;
        long long int sum=0;
        FILE *f = fopen(argv[1], "r");

        if (!f) {
            exit(EXIT_FAILURE);
        }
        fscanf(f, "%ld", &N);

        struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) );

        graph->edge = (struct Edge*) malloc( N * sizeof( struct Edge ) );
        for (i = 0; i < N-1; i++) {
            fscanf(f, "%ld", &n1);
            fscanf(f, "%ld", &n2);
            fscanf(f, "%ld", &w);

            graph->edge[i].src = n1;
            graph->edge[i].dest = n2;
            graph->edge[i].weight = w;
        }

        long int x,y;
        struct Edge next_edge ;

        qsort(graph->edge, N-1, sizeof(graph->edge[0]), comp);

            /*
        for (i = 0; i < N -1 ; i++)
        {
            printf("%ld\t %ld\t %ld\n", graph->edge[i].src, graph->edge[i].dest,             graph->edge[i].weight); 
        }
         */
        // Allocate memory for creating V subsets
        struct subset *subsets = (struct subset*) malloc( N * sizeof(struct subset) );
        // Create V subsets with single elements
        for (j = 0 ; j < N ; j++)
        {
                subsets[j].parent = 0;
            subsets[j].rank = 0;
            subsets[j].vertex = 1 ; 
        }

        i = 0; 
        while (i < N-1)
        {
            next_edge = graph->edge[i--];
            x = find(subsets, next_edge.src);
            y = find(subsets, next_edge.dest);
            if (x != y){
                      sum += graph->edge[i].weight + ( ( graph->edge[i].weight +1 ) * (subsets[x].vertex*subsets[y].vertex-1));
                Union(subsets, x, y);
            }
        }

        printf("%lld\n", sum);

        return 0 ;
       } 

PS The purpose of the program is, given an MST, to calculate the weight of a full tree in a way that the given MST is its only MST. PS该程序的目的是给定一个MST,以给定MST为其唯一MST的方式计算一棵完整树的权重。

The probable cause it his loop: 可能的原因是他的循环:

i = 0; 
while (i < N-1)
{
    next_edge = graph->edge[i--];
    ...
}

Here you start out with index zero, then decrease it . 在这里,您从索引零开始,然后将其减小 So when you use i as index later in the loop it will have the value -1 and you will index out of bounds for the allocated memory, leading to undefined behavior . 因此,当您在循环的稍后部分将i用作索引时,其值将为-1并且索引将超出分配的内存范围,从而导致未定义的行为 The loop itself may also run for as long as i is negative, until it underflows to become the max signed long value (so you will loop over two billion times). 只要i为负,循环本身也可以运行直到它下溢成为最大有符号long值为止(因此,您将循环20亿次以上)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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