嵌套for循环中的分段错误,具有动态内存分配

时间:2018-06-03 17:10:01

标签: c for-loop nested nested-loops dynamic-memory-allocation

我正在准备使用C模拟距离矢量路由的代码,但是,我在运行时遇到了分段错误。 代码: -

raw

我在执行期间在终端上输出了以下输出。

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

/* Date : 03/06/2018
 *
 * Algorithm
 *
 * 1. get number of nodes from user
 * 2. dynamic alloc new matrix nxn
 * 3. create distance vector matrix, if dist > 1000 consider inf
 * _|   A   B   C   D   E   F
 * A|   0   5   2   3   i   i
 * B|   5   0   4   5   
 * C|
 * D|
 * E|
 * F|
 * ---------------
 *
 * 4. create new routing matrix of nxn
 * 5. create new minimizing array for the node
 * 6. find minimum of the array, allocate new value
 *
 * copyleft
 */

#define inf 1000

int min_r(int*, int*, int);
void dvr(int**, int**, char**, int);
void dvtDisp(int**, int);
void dvtDispNew(int **, char**, int);

int main(){
    int n;                              //No of nodes
    int i,j;                            //Counters

    printf("> enter the number of nodes in the network... ");
    scanf("%d",&n);

    int **DisMat = (int **)malloc(n * n * sizeof(int));     //Dynamic allocation of Distance Matrix

    for(i=0; i<n; i++){                     // x directional loop
        printf("> distance vector table for node %c\n",i+65);
        for(j=0; j<n; j++){                 // y directional loop
            printf("> distance from %c... ",j+65);
            if(j==i) { DisMat[i][j] = 0; printf("0");}
            else scanf("%d",&DisMat[i][j]);
        }// y directional loop
    }// x directional loop

    int **NewDisMat = (int **)malloc(n * n * sizeof(int));      //New Distance Matrix
    char **Hop = (char **)malloc(n * n * sizeof(char));     //New Hop Matrix

    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            Hop[i][j] = '-';                //All Hops Nullified
        }
    }

    dvr(DisMat, NewDisMat, Hop, n);                 //Distance Vector Routing

    return 0;
}//main

void dvr(int *dvt[], int *newdvt[], char *hopper[], int l){     //DVR function
    int x=0, y=0, z=0, conCount;
    int hopPoint;
    int *mini = (int *)malloc((l-1) * sizeof(int));
    int *mzer = (int *)malloc((l-1) * sizeof(int));

    for(x=0; x<l; x++){                     // x directional propagation
        mini[0] = x;
        z = 1; conCount=0;
        do{
            if((dvt[x][y] < inf) && (y != x)) {
                mini[z] = y;
                z++;
                conCount++;
            }
            y++;
        }while(y<l);

        y = 0; z = 0;

        for(y = 0; y<l; y++){
            while(z<conCount){
                mzer[z] = dvt[mini[z]][y];
                z++;
            }

            newdvt[x][y] = min_r(mzer, &hopPoint, conCount);
            hopper[x][y] = hopPoint + 65;
        }// y directional propagation
    }// x directional propagation
}//dvr

int min_r(int arr[], int *index, int len){
    //Sequential minimum search
    int min;
    int ind = 0;

    min = arr[ind];
    for(ind = 0; ind<len; ind++){
        if(arr[ind] < min){
            min = arr[ind];
            *index = ind;
        }
    }

    return min;
}//min_r

void dvtDisp(int *dvt[], int size){
    int x, y;
    printf("_ |");

    for(x = 0; x<size; x++){
        printf("\t%c",65 + x);
    }
    printf("\n");

    for(y = 0; y<size; y++){
        printf("%c |",y + 65);

        for(x = 0; x < size; x++)
            printf("\t%d",dvt[x][y]);
    }
}

void dvtDispNew(int *dvt[], char *hopto[], int size){
    int x, y;
    printf("_ |");

    for(x = 0; x<size; x++){
        printf("\t%c\thop",65 + x);
    }
    printf("\n");

    for(y = 0; y<size; y++){
        printf("%c |",y + 65);

        for(x = 0; x < size; x++)
            printf("\t%d\t%c",dvt[x][y],hopto[x][y]);
    }
}

我试图在gdb上运行它,但无法弄清楚结果意味着什么。这里是gdb输出: -

anwesh@bionic-Inspiron:~/Documents/NS2/LAB/prog5$ gcc main.c
anwesh@bionic-Inspiron:~/Documents/NS2/LAB/prog5$ ./a.out
> enter the number of nodes in the network... 5
> distance vector table for node A
Segmentation fault (core dumped)

最初我认为这是一个与动态内存分配有关的问题,但我不知道具体原因。我已多次检查代码,看看是否有任何天真的错误,但我不能。

请帮帮我吧!提前谢谢。

1 个答案:

答案 0 :(得分:1)

该行

int **DisMat = (int **)malloc(n * n * sizeof(int));     //Dynamic allocation of Distance Matrix

无效。 DisMat是一个指向int数组的指针数组。所以我们需要首先为int分配n个指针:

int **DisMat = malloc(n * sizeof(int*));

然后我们需要n次分配n个int的数组:

for(size_t i = 0; i < n; ++i) {
    DisMat[i] = malloc(n * sizeof(int));
}

HopNewDisMat也是如此。

请记住,malloc不会检查乘法溢出。

以下代码运行良好:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>

/* Date : 03/06/2018
 *
 * Algorithm
 *
 * 1. get number of nodes from user
 * 2. dynamic alloc new matrix nxn
 * 3. create distance vector matrix, if dist > 1000 consider inf
 * _|   A   B   C   D   E   F
 * A|   0   5   2   3   i   i
 * B|   5   0   4   5   
 * C|
 * D|
 * E|
 * F|
 * ---------------
 *
 * 4. create new routing matrix of nxn
 * 5. create new minimizing array for the node
 * 6. find minimum of the array, allocate new value
 *
 * copyleft
 */

#define inf 1000

int min_r(int*, int*, int);
void dvr(int**, int**, char**, int);
void dvtDisp(int**, int);
void dvtDispNew(int **, char**, int);

int main(){
    int n;                              //No of nodes
    int i,j;                            //Counters

    printf("> enter the number of nodes in the network... ");
    scanf("%d",&n);

    int **DisMat = malloc(n * sizeof(*DisMat));     //Dynamic allocation of Distance Matrix
    assert(DisMat != NULL);
    for(size_t i = 0; i < n; ++i) {
        DisMat[i] = malloc(n * sizeof(*DisMat[i]));
        assert(DisMat[i] != NULL);
    }

    for(i=0; i<n; i++){                     // x directional loop
        printf("> distance vector table for node %c\n",i+65);
        for(j=0; j<n; j++){                 // y directional loop
            printf("> distance from %c... ",j+65);
            if(j==i) { DisMat[i][j] = 0; printf("0");}
            else scanf("%d",&DisMat[i][j]);
            printf("\n");
        }// y directional loop
    }// x directional loop

    int **NewDisMat = malloc(n * sizeof(*NewDisMat));      //New Distance Matrix
    assert(NewDisMat != NULL);
    for(size_t i = 0; i < n; ++i) {
        NewDisMat[i] = malloc(n * sizeof(*NewDisMat[i]));
    assert(NewDisMat[i] != NULL);
    }
    char **Hop = malloc(n * sizeof(*Hop));     //New Hop Matrix
    assert(Hop);
    for(size_t i = 0; i < n; ++i) {
        Hop[i] = malloc(n * sizeof(*Hop[i]));
        assert(Hop[i] != NULL);
    }

    for(i=0; i<n; i++){
        for(j=0; j<n; j++){
            Hop[i][j] = '-';                //All Hops Nullified
        }
    }

    dvr(DisMat, NewDisMat, Hop, n);                 //Distance Vector Routing

    for(size_t i = 0; i < n; ++i) {
         free(DisMat[i]);
    }
    free(DisMat);
    for(size_t i = 0; i < n; ++i) {
         free(NewDisMat[i]);
    }
    free(NewDisMat);
    for(size_t i = 0; i < n; ++i) {
         free(Hop[i]);
    }
    free(Hop);
    return 0;
}//main

void dvr(int *dvt[], int *newdvt[], char *hopper[], int l){     //DVR function
    int x=0, y=0, z=0, conCount;
    int hopPoint;
    int *mini = (int *)malloc((l-1) * sizeof(int));
    int *mzer = (int *)malloc((l-1) * sizeof(int));

    for(x=0; x<l; x++){                     // x directional propagation
        mini[0] = x;
        z = 1; conCount=0;
        do{
            if((dvt[x][y] < inf) && (y != x)) {
                mini[z] = y;
                z++;
                conCount++;
            }
            y++;
        }while(y<l);

        y = 0; z = 0;

        for(y = 0; y<l; y++){
            while(z<conCount){
                mzer[z] = dvt[mini[z]][y];
                z++;
            }

            newdvt[x][y] = min_r(mzer, &hopPoint, conCount);
            hopper[x][y] = hopPoint + 65;
        }// y directional propagation
    }// x directional propagation
}//dvr

int min_r(int arr[], int *index, int len){
    //Sequential minimum search
    int min;
    int ind = 0;

    min = arr[ind];
    for(ind = 0; ind<len; ind++){
        if(arr[ind] < min){
            min = arr[ind];
            *index = ind;
        }
    }

    return min;
}//min_r

void dvtDisp(int *dvt[], int size){
    int x, y;
    printf("_ |");

    for(x = 0; x<size; x++){
        printf("\t%c",65 + x);
    }
    printf("\n");

    for(y = 0; y<size; y++){
        printf("%c |",y + 65);

        for(x = 0; x < size; x++)
            printf("\t%d",dvt[x][y]);
    }
}

void dvtDispNew(int *dvt[], char *hopto[], int size){
    int x, y;
    printf("_ |");

    for(x = 0; x<size; x++){
        printf("\t%c\thop",65 + x);
    }
    printf("\n");

    for(y = 0; y<size; y++){
        printf("%c |",y + 65);

        for(x = 0; x < size; x++)
            printf("\t%d\t%c",dvt[x][y],hopto[x][y]);
    }
}

旁注:请记住sizeof(int*) == sizeof(*DisMat),所以我更喜欢:

int **DisMat = malloc(n * sizeof(*DisMat));

通过使用该表达式type *variable = malloc(n * sizeof(*variable)),我记得,我正在分配正确的类型,在DisMat的情况下指向int的指针数组,导致typeof(*DisMat) == int*,并减少错误。